Mike159 Mike159 - 2 months ago 9
C# Question

C# List definition, parentheses vs curly braces

I've just noticed that when you declare a

in c# you can put parentheses or curly braces at the end.

List<string> myList = new List<string>();
List<string> myList2 = new List<string>{};

Both these list appear to have the same functionality. Is there any actual difference caused by declaring them with parentheses or curly braces?


The use of curly braces { } is called a collection initializer. For types that implement IEnumerable the Add method would be invoked normally, on your behalf:

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

Empty collection initializers are allowed:

List<string> myList2 = new List<string>() { };

And, when implementing an initializer, you may omit the parenthesis () for the default constructor:

List<string> myList2 = new List<string> { };

You can do something similar for class properties, but then it's called an object initializer.

var person = new Person
                     Name = "Alice",
                     Age = 25

It is possible to combine these:

var people = new List<Person>
                     new Person
                             Name = "Alice",
                             Age = 25
                     new Person
                             Name = "Bob"

This language feature introduced in C# 3.0 also supports initializing anonymous types, which is especially useful in LINQ query expressions:

var person = new { Name = "Alice" };

They also work with arrays, but you can further omit the type which is inferred from the first element:

var myArray = new [] { "one", "two", "three" };

And initializing multi-dimensional arrays goes something like this:

var myArray = new string [,] { { "a1", "b1" }, { "a2", "b2" }, ... };