C# - What are object initializers and what do they do?

I had a conversation the other day on the topic of object initializers and what they do. In this post I will briefly elaborate on what they are and how they work. There is some extensive documentation on microsoft.com on this topic - however this post is just showing the essentials

The use of object initializers

So let us say we have the following class, which is really simple. It has two public properties: Name and Lastname.

public class Person
{
    public string Name { get; set; }
    public string Lastname { get; set; }
}

Using an object initializer you can create a new object of this type and assign values to it using the following:

var person = new Person
{
   Name = "Peter",
   Lastname = "Rasmussen"
};

Using the above code you now have an object with the values "Peter" and "Rasmussen". What you have basically done is the following:

var person = new Person();
person.Name = "Peter";
person.Lastname = "Rasmussen";

You have created a new object and assigned some values to its properties. The above is what the compiler will see. The object initializer is just sugar syntax that makes your code easier to read. It will also help you avoid assigning to the wrong object or assign to the same property twice (copy paste eh?). Which is an easy mistake to make if you have many assignments after one another.

Combining the two

As You can see in the first example, there was no parenthesis () after the new Person when using the object initializer. These are not needed, if you are using a default constructor. However you can easily use a constructor together with the initializer - combining the two if you wish. Which is simply done by adding a constructor:

public class Person
{
    private string _middleName;

    public Person(string middleName)
    {
        _middleName = middleName;
    }

    public string Name { get; set; }
    public string Lastname { get; set; }
}

Then you can use this together with an initializer:

var person = new Person("Daugaard")
{
    Name = "Peter",
    Lastname = "Rasmussen"
};

In the above an initializer and constructor are combined. Often on DTO's you will only use properties. However the above is constructed to show that they can be combined and used together - even if this scenario might be rare. The above would be equivalent to writing the following:

var person = new Person("Daugaard");
person.Name = "Peter";
person.Lastname = "Rasmussen";

I hope you liked my short explanation of object initializers, if you did or did not, let me know in the comments!