C# List definition, parentheses vs curly braces

前端 未结 4 1815
抹茶落季
抹茶落季 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

    They have different semantics.

    List myList = new List();
    

    The above line initializes a new List of Strings, and the () is part of the syntax of building a new object by calling its constructor with no parameters.

    List myList2 = new List{};
    

    The above line initializes a new List of Strings with the elements presented inside the {}. So, if you did List myList2 = new List{"elem1", "elem2"}; you are defining a new list with 2 elements. As you defined no elements inside the {}, it will create an empty list.

    But why does the second line have no () ?

    That makes part of a discussion in which omitting the parenthesis in this case represents a call to the default constructor. Take a look at This Link

提交回复
热议问题