Search code examples
c#object-initializers

Object initializer syntax confusion. Using parentheses in initializer?


So I was looking at the documentation to understand how to use an object initializer, be it for anonymous types or not. The only thing that I would like to find out is why(and if it matters) is there a difference in the example.

It goes like this: for a Cat

class Cat
{
    public int Age { get; set; }
    public string Name { get; set; }
}

I can see the first example like so:

Cat cat = new Cat { Age = 10, Name = "Fluffy" };

This makes sense. But then, you can find the following:

List<Cat> cats = new List<Cat>
{
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 }
};

Now my question is: (why) is there a difference between new Cat{...} and new Cat(){...} ? Why should we use(or not) the parentheses?


Solution

  • If an object has a parameterless constructor, you can omit the parentheses. So both of these are valid

    // Assuming cat has a constructor with no parameters
    Cat cat = new Cat { Age = 10, Name = "Fluffy" };
    Cat cat = new Cat() { Age = 10, Name = "Fluffy" };
    

    The List<T> itself has an object initializer where you can provide any number of items, and they are automatically added to the collection.

    List<Cat> cats = new List<Cat>()
    {
        new Cat(){ Name = "Sylvester", Age=8 }, // Add sylvester to the List
        new Cat(){ Name = "Whiskers", Age=2 } // And Whiskers too
    };
    

    As mentioned above you can also remove the parentheses here aswell

    List<Cat> cats = new List<Cat>
    {
        new Cat { Name = "Sylvester", Age=8 }, // Add sylvester to the List
        new Cat { Name = "Whiskers", Age=2 } // And Whiskers too
    };