Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Initializer list - when to use () operator after class name?

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.

like image 700
Yechiel Labunskiy Avatar asked Jan 20 '13 10:01

Yechiel Labunskiy


2 Answers

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.

like image 195
user1908061 Avatar answered Nov 09 '22 11:11

user1908061


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.

like image 31
Oded Avatar answered Nov 09 '22 13:11

Oded