1

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"}; 

2 Answers2

1

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");
adjan
  • 13,371
  • 2
  • 31
  • 48
0

Into () brackets (constructor) you can pass some specific parameters like initial size of the list etc. When using { } brackets, you just initialize the list with some start values.

In your case it makes no difference which you will use, both will have similar effect as you use default constructor call.

pitersmx
  • 935
  • 8
  • 27