Reputation: 363
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" }
};
Upvotes: 3
Views: 139
Reputation: 23646
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
Upvotes: 3
Reputation: 564871
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.
Upvotes: 6