Object Initializers in C#

Comments [0]

Back To Basics

Prior to C# 3.0, we had two common ways to initialize the public properties of an object.

  1. We could use the default constructor to instantiate the object; then, use a separate line of code to assign a value to each property. (Listing 1)
  2. We could create a constructor that accepts an argument for each property; and write code in this constructor to assign to each public property the value passed in for each corresponding argument. (Listing 2 and Listing 3)

The first method is quite verbose and requires a lot of code for complex objects.

Listing 1:

Customer cust1 = new Customer();
cust1.CustomerID = 1;
cust1.FirstName = "George";
cust1.LastName = "Washington";
cust1.StreetAddress = "111 A St";
cust1.City = "Aville";
cust1.State = "MI";
cust1.ZipCode = "10001";

Listing 2:

class Customer
{
    public Int32 CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public Customer
        (
        Int32 customerID,
        string firstName,
        string lastName,
        string streetAddress,
        string city,
        string state,
        string zipCode
        )
    {
        CustomerID = customerID;
        FirstName = firstName;
        LastName = lastName;
        StreetAddress = streetAddress;
        City = city;
        State = state;
        ZipCode = zipCode;
    }
}

Listing 3:

Customer cust2 = new Customer
    (
    2,
    "John",
    "Adams",
    "222 B Ave",
    "Beetown",
    "MI",
    "20002"
    );

The second method is more elegant, but assumes we always want to initialize every single public property at object instantiation. Of course, we could create multiple constructors to accommodate times when we only want to initialize certain variables but this can get complex in a hurry when our class has a lot of public properties.

Beginning with C# 3.0, we can now initialize public properties in the same line of that instantiates an object; and we can do so without creating a new constructor. We use object initializers to do this. 

Using object initializers we can still use the default constructor (or any public constructor we want); but we can set public properties by appending the property assignments within a set of curly braces at the end of the object initializer, as shown in listing 4.

Listing 4:

Customer cust4 = new Customer() 
            {   CustomerID = 4, 
                FirstName = "James", 
                LastName = "Monroe" 
            };

This new C# feature is known as object initializers. This method gives us a great deal of flexibility. At the time we instantiate an object, we can decide which properties to initialize. And we can do so without creating a plethora of constructors for the object or return to the verbose way of assigning property values after an object's instantiation.

Object initializers are most useful when you instantiate a class in many different places throughtout an application.

Download this code to view and run a simple application that uses object initializers DemoObjectInitializers.zip (24.92 KB)