C# – Creating Object Parameters in {}

c

I am trying to decode a piece of code from a book:

List<Person> people = new List<Person>()
{
new Person {FirstName="Homer",LastName="Simpson",Age=47},
new Person {FirstName="Marge",LastName="Simpson",Age=45}
};

Person is just a simple class they made, with a bunch of fields: Name, Last Name, etc…

What I don't understand is, don't we send parameters to a constructor of Person in non-curly brackets? I tried replicating this code, but it doesn't seem to fly, any takers?

Thanks for input.

Best Answer

C# allows you to specify property parameters in curly braces when the object is initialized. This allows you to pick and choose which items to initialize and which to leave as defaults.

A constructor, on the other hand, runs one single block of code with a fixed set of parameters. So to get the same effect you'd have to create multiple constructors all with the various combinations of properties you might want to initialize, which could be tedious.

var x = new Person {FirstName="Homer",LastName="Simpson",Age=47}; 

is exactly equivalent to this:

var x = new Person();
x.FirstName="Homer";
x.LastName="Simpson";
x.Age=47;

Except that it's shorter and arguably easier on the eyes.

It also allows for constructs like you demonstrated in your question, which would be very tedious if you had to create temporary variables and initialize them out as I did here before adding them to the list. (Which is how you used to have to do it.) All without requiring an explicitly-defined constructor that takes your desired list of parameters, which may or may not be available.

Also, note that while a constructor can initialize properties with a private setter, this technique (as should be obvious from the provided example) will only work if you have a public setter for the property. Also note that my shortened example implicitly called the default (parameterless) constructor, which would therefore have to be present.

Related Topic