Search code examples
c#listinitializer

Creating List from initializer


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


Solution

  • 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"
    };