Object Initializers

Although you normally set the properties of your object with a constructor, that’s not the only way to do it. C# also offers object initializers, which let you set any accessible members of your object when you create it. Notice that we said accessible, which means you can set public members, but not private ones. Suppose you have this Dog class, with member fields that are public:

public class Dog
{
    public string name;
    public int weight;

    // constructor
    public Dog(string myName)
    {
        name = myName;
    }
}

Notice here that the constructor takes a string to set the dog’s name, but it doesn’t take a weight. That’s fine, because weight is public, so you could easily set it later, like this:

Dog milo = new Dog("Milo");
Milo.weight = 5;

With an object initializer, though, you can set the public weight immediately after you create the object, like this:

Dog milo = new Dog("Milo") { weight = 5 };

There’s not a whole lot of reason to do this; you could just rewrite the constructor to accept the weight. In fact, it’s generally a bad idea to have your member fields be public, as we’ve said. However, this technique has some advantages with anonymous types.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.