简体   繁体   中英

What is the difference between c# List creation in following program

In following c# program, what is the difference between l1 and l2?

First Console output is False. Second Console output is True.. Why?

class Program
{
    public static void Main(string[] args)
    {
        List<string> l1 = new List<string>();
        l1.Clear();
        l1.Add("test1");

        List<string> l2 = new List<string>(l1);

        List<string> l3 = l1;

        List<string> l4 = l1;

        Console.WriteLine(l2 == l3);

        Console.WriteLine(l3 == l4);
    }
}

List<T> is a reference type, all you are doing is copying the reference, in essence multiple variables can contain the same reference... Then when you call == its basically telling you it is the same reference

Think of a reference as a piece of paper with someones name written on it. When you call something liek this

 List<string> l3 = l1;
 List<string> l4 = l1;

All you are doing (in the case of a reference type), is copying the name, not the person

Read more here Reference types (C# Reference)

There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects) , while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable . With value types, each variable has its own copy of the data, and it is not possible for operations on one variable to affect the other (except in the case of in, ref and out parameter variables; see in, ref and out parameter modifier).

Very Less Technically Speaking , L1 , L3, L4 shares same house (ie Reference) and Utensils (ie Items in list) whereas L2 lives in different house but that house is structured as per L1's house and even he brought utensils similar to L1.

When you do this --

List<string> l2 = new List<string>(l1);

A new List(house) for L2 is created which has same items as L1. But when You do this --

 List<string> l3 = l1;

L3 is referred to L1's List and L3 can directly access and manipulate L1's Items Which means if L3 delete any item , L1 will also Loose that Item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM