Domanda

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...

È stato utile?

Soluzione

It's the same. From MSDN:

The object initializer syntax enables you to specify arguments for a constructor or omit the arguments (and parentheses syntax)

The same rule applies to list and ordinary object initializers:

var foo = new Bar {
    Prop = "value"
};

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top