Reputation: 1833
Is there any difference between
var list = new List<UserType>
{
new UserType(...),
new UserType(...),
};
and
var list = new List<UserType>()
{
new UserType(...),
new UserType(...),
};
?
I used to use always the second one thinking that I'm just required to call the list's parameterless (or any other) constructor...
Upvotes: 2
Views: 64
Reputation: 126042
No, there is no difference. The IL generated is exactly the same:
IL_0001: newobj System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006: stloc.1 // <>g__initLocal0
IL_0007: ldloc.1 // <>g__initLocal0
IL_0008: newobj UserQuery+UserType..ctor
IL_000D: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012: nop
IL_0013: ldloc.1 // <>g__initLocal0
IL_0014: newobj UserQuery+UserType..ctor
IL_0019: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_001E: nop
IL_001F: ldloc.1 // <>g__initLocal0
IL_0020: stloc.0 // list
Even instantiating a new List
and calling .Add
yourself is quite similar, i.e.:
var list = new List<UserType>();
list.Add(new UserType());
list.Add(new UserType());
... generates:
IL_0001: newobj System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006: stloc.0 // list
IL_0007: ldloc.0 // list
IL_0008: newobj UserQuery+UserType..ctor
IL_000D: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012: nop
IL_0013: ldloc.0 // list
IL_0014: newobj UserQuery+UserType..ctor
IL_0019: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
Which is slightly different -- looks like the difference is generating a temporary variable and assigning it to list
vs creating and manipulating list
directly.
Upvotes: 3