Sometimes an initializer list is specified after the class name without using the () operator:
Cat cat = new Cat { Age = 10, Name = "Fluffy" }
Other times it is specified after the () operator:
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 }
}
I am assuming the difference is because here new Cat() is inside the list. But I still don’t understand why it should be different. So why the difference, and when to use which syntax?
Thanks.
When you use the initializer list you can omit the (), when using a parameterless constructor. It does not matter with the new Cat() is inside the list or not.