Does a name exist for the parenthesis after new()?

c#

Solution

This is called object initializer. For instance let we have a class called `Customer`, whose definition is the following one:

public class Customer
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName  { get; set; }
    public int Age { get; set; }
}

Then you could instantiate an object of type `Customer` like below:

Customer customer = new Customer 
{ 
    ID = 0, 
    FirstName="firstName", 
    LastName="lastName", 
    Age = 20 
};

In a few words it's another way to instantiate an object.

What happens behind the scenes, when we use an object initializer?

The default empty constructor of `Customer` is called:

Customer customer = new Customer();

and then the propertie's setter's are called in the order they have written in the object initializer:

customer.ID = 0;
customer.FirstName = "firstName";
customer.LastName = "lastName";
customer.Age = 20;

Furthermore, a notion close to object initializer is the collection initializer.

Instead of writing this:

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);

we could write this:

List<int> numbers = new List<int>() { 1, 2, 3, 4 };

which is definetely more compact that the initial version and I would say also more expressive. In the above example, we used a collection initializer.

What happens behind the scenes, when we use a collection initializer?

If we take the last example, it happens exactly this:

// Create the a new list
List<int> numbers = new List<int>();

// Add one element after the other, in the order they appear in the
// collection initializer, using the Add method.
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);

For more information about object and collection initializers, please visit this link.

Last but not least, I would like to point out that object and collection initializers got introduced in C# 3.0. Unfortunately, If you had to write an application in days of C# 2.0 you hadn't this feature available.

Problem

I wanted to inquire more about a construct I occasionally see in some C# code; however, I don't know the name. I apologize if this is a duplicate; however, its very hard to search for things without knowing their name. The construct is as follows: ``` Person me = new Person(){ Name = "Aelphaeis" } ; ``` Is there a special name for assigning fields/properties like this?

Original source