Search code examples
c#.netlistinitializationcollection-initializer

Initialization of list in class for availability from functions


I want initialize list with collection initializer values in class to make it available to use from separate functions:

public Form1()
{
    InitializeComponent();
}

List<string> list = new List<string>() {"one", "two", "three"}; 

What is a difference of list with brackets and without, which one is proper for this case:

List<string> list = new List<string> {"one", "two", "three"}; 

Solution

  • Calling

    List<string> list = new List<string> {"one", "two", "three"}; 
    

    is just a shorthand and implicitly calls the default constructor:

    List<string> list = new List<string>() {"one", "two", "three"}; 
    

    Also see the generated IL code, it is the same:

    List<string> list = new List<string>() {"one"}; 
    List<string> list2 = new List<string> {"one"}; 
    

    becomes:

    IL_0001:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
    IL_0006:  stloc.2
    IL_0007:  ldloc.2
    IL_0008:  ldstr      "one"
    IL_000d:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
    IL_0012:  nop
    IL_0013:  ldloc.2
    IL_0014:  stloc.0
    
    IL_0015:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
    IL_001a:  stloc.3
    IL_001b:  ldloc.3
    IL_001c:  ldstr      "one"
    IL_0021:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
    IL_0026:  nop
    IL_0027:  ldloc.3
    IL_0028:  stloc.1
    

    You see that the {} notation is just syntactical sugar that first calls the default constructor and then adds every element inside the {} using the List<T>.Add() method. So your code is equivalent to:

    List<string> list = new List<string>();
    list.Add("one");
    list.Add("two");
    list.Add("three");