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.
You must specify the ()
when there is no default (parameterless) constructor - when you have to supply parameters.
When a class has default constructor (or a parameterless one), you can always omit the ()
when using an initializer. The compiler does the magic for you and you can think of things as - the compiler inserts them for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With