3

I admit I'm far from experienced with c#, so this may be obvious, but I have to ask -- is there any difference between the two code samples? In case it's not obvious, the first statement omits () at the end of new operator. Is there any difference there or is () simply redundant in this context?

private static Dictionary<string, string> dict1 = new Dictionary<string, string>
{
    { "a", "A" },
    { "b", "B" }
};

private static Dictionary<string, string> dict2 = new Dictionary<string, string>()
{
    { "a", "A" },
    { "b", "B" }
};
ADSMarko
  • 363
  • 1
  • 3
  • 8
  • There is no difference but for readability in regards to having someone else read and or support your code I think that most C# coders are familiar with declaring the Dictionary new using the second example. keep in mid also that if you were create a `Dictionary dict1 = new Dictionary;` without `()` as a non method then you would get compiler error – MethodMan Mar 15 '13 at 16:07
  • @DJ KRAZE, I know `Dictionary dict1 = new Dictionary;` wouldn't compile and that's why it surprised me that both of my examples do compile. – ADSMarko Mar 15 '13 at 16:12
  • it's different when declaring a method ver an Instance – MethodMan Mar 15 '13 at 16:17

2 Answers2

6

Is there any difference there or is () simply redundant in this context?

There is no difference. Adding the () is optional when using a collection initializer, but the resulting compiled IL is identical.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

No, there isn't. If you would inspect IL code, you would see no difference between two constructor calls:

IL_0028:  newobj      System.Collections.Generic.Dictionary<System.String,System.String>..ctor
IL_002D:  stloc.1     // <>g__initLocal1
IL_002E:  ldloc.1     // <>g__initLocal1
IL_002F:  ldstr       "a"
IL_0034:  ldstr       "A"
IL_0039:  callvirt    System.Collections.Generic.Dictionary<System.String,System.String>.Add
IL_003E:  ldloc.1     // <>g__initLocal1
IL_003F:  ldstr       "b"
IL_0044:  ldstr       "B"
IL_0049:  callvirt    System.Collections.Generic.Dictionary<System.String,System.String>.Add
IL_004E:  ldloc.1     // <>g__initLocal1
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90