C# List definition, parentheses vs curly braces

前端 未结 4 1802
抹茶落季
抹茶落季 2020-12-09 16:00

I\'ve just noticed that when you declare a List in c# you can put parentheses or curly braces at the end.

List myList = new List&l         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 17:00

    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 myList2 = new List() { "one", "two", "three" };
    

    Empty collection initializers are allowed:

    List myList2 = new List() { };
    

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

    List myList2 = new List { };
    

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

    var person = new Person
                     {
                         Name = "Alice",
                         Age = 25
                     };
    

    And its possible to combine these:

    var people = new List
                     {
                         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" }, ... };
    

    Update

    Since C# 6.0, you can also use an index initializer. Here's an example of that:

    var myDictionary = new Dictionary
                           {
                               ["one"] = 1,
                               ["two"] = 2,
                               ["three"] = 3
                           };
    

提交回复
热议问题