0

E.g. is there any technical difference between invoking:

List<string> list = new List<T> () { "one", "two", "tree" };  // with ()

and

List<string> list = new List<T> { "one", "two", "tree" };    // without ()

?

The result is obviously the same. But I am interested if there is any technical difference in the way of invocation or this is only a convenience .NET C# shortcut.

Chris W
  • 1,562
  • 20
  • 27
  • No difference, Empty Argument is totally needless in this case – Pankaj Jun 27 '14 at 08:00
  • @Pankaj: that it's needless is not an indication whether it is _required_ or not. – Tim Schmelter Jun 27 '14 at 08:05
  • 1
    Related and informative: [Why are object initializer constructor parentheses optional?](http://stackoverflow.com/questions/3661025/why-are-c-sharp-3-0-object-initializer-constructor-parentheses-optional) – Tim Schmelter Jun 27 '14 at 08:12

2 Answers2

5

There is no difference. The parenthesis are not required when using a collection initializer with the default constructor. However, if you want to use another constructor you cannot omit the parenthesis.

Some code refactoring tools like ReSharper will indicate this by showing the parenthesis as redundant.

Collection initializers are not limited to "built-in" .NET types. A type implementing IEnumerable and providing a suitable Add method can use a collection initializer.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
1

Both will actualy compile into

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

if you check generated IL code.

Atomosk
  • 1,871
  • 2
  • 22
  • 26
  • Collection initializer version create initialize temp list and then set reference to actual variable. IL's for both are not same. – Rohit Vats Jun 27 '14 at 08:03
  • @RohitVats Yes collection initializer creates temporary local variable, but for both versions: with parentheses and without parentheses IL is same. Corrected code to better represent generated IL. – Atomosk Jun 27 '14 at 08:29