TIL Tuesday: Object Initializers in C#

TIL there is a convenient shorthand way of setting public members of an object when defining a new instance.

Imagine have a class 'Animal' with public properties such as its name and how many legs it has. For object initializers to work correctly the class we're initializing must have a public, parameterless constructor.

public class Animal
{
    public string Name { get; set; }
    public int NumLegs { get; set; }

    public Animal() { }

    public override string ToString()
    {
        return Name + " has " + NumLegs + " legs.";
    }
}

Traditionally we'd initialize an object of the Animal class by creating a new variable in one statement and then populate its members one-by-one in the following statements.

var critter = new Animal();
critter.Name = "Bear";
critter.NumLegs = 4;

But with an object initializer, we can populate the public members in the same statement that the object is declared:

var creature = new Animal
{
    Name = "Penguin",
    NumLegs = 2
};

The initializer is just a block that follows the class' name when you're declaring a new object of a class with a parameterless constructor.

You don't have to populate all of the public properties, only the ones you want.