BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 3.0+

C# Object Initializers

C# 3.0 introduces a new feature that configures the properties of newly instantiated objects. Object initializers allow multiple property values to be set within a single assignment operation. They are used in conjunction with any provided constructors.

Initialising Object Properties

Prior to the availability of object initializers, there were two standard ways to set the properties of a new object. In most cases, an object could be instantiated and its properties set individually over a number of lines of code. Alternatively, a parameterised constructor could be created that allowed the initial state for the object to be specified. This constructor would use the parameters to set the properties of the new object and, possibly, perform other initialisation tasks.

When using C# 3.0 and the .NET framework 3.0 or later, a third option, known as an object initializer, is available. Object initializers provide a simplified syntax for specifying initial values for one or more properties of an object. A simple list of properties and their respective values is added to the object's declaration. This is converted by the compiler into a series of calls to the properties' set accessors. These are executed after any appropriate constructors have been processed.

Object initializers should not be considered as a replacement for the correct use of constructors. With constructors, you can ensure that a newly generated object is in a valid state, which is a requirement of good object-oriented programming technique. The use of an object initializer is optional and you can choose which properties to set and which to ignore. Relying solely on an initializer can therefore potentially create an invalid object state.

Simple Object Initializer

To demonstrate the use of object initializers we need a class to instantiate. We will use a simple class that represents an employee in a human resources system. This class has properties for the person's payroll number, name, salary and holiday entitlement. Using automatically implemented property syntax, the code for the class is as follows:

class Employee
{
    public int PayrollNumber { get; set; }
    public string FirstName { get; set; }
    public string MiddleNames { get; set; }
    public string LastName { get; set; }
    public float Salary { get; set; }
    public int Holidays { get; set; }
}

To create an employee object and set some of the properties using pre-C# 3.0 syntax, you can use code that is similar to the following:

Employee emp = new Employee();
emp.PayrollNumber = 1;
emp.FirstName = "Bob";
emp.LastName = "Smith";
emp.Salary = 35000;
emp.Holidays = 25;

Using the object initializer syntax, a single statement can be used to declare the new employee object and set the same property values. The values are simply provided in a comma-separated list in a code block following the "new Employee" section. As the default constructor is being used, the parentheses are optional. The following code recreates the previous sample's functionality. It is shown on several lines for readability but could appear as a single line of code if preferred.

Employee emp = new Employee
{
    PayrollNumber = 1,
    FirstName = "Bob",
    LastName = "Smith",
    Salary = 35000,
    Holidays = 25
};

Using Object Initializers with Constructors

As mentioned earlier, object initializers are not a good replacement for constructors. It may be that the Employee object is only considered to be in a valid state if a payroll number and last name are present. We cannot guarantee that this will be the case using the default constructor. Instead, we should add a custom constructor to the Employee class as follows. NB: This code is for demonstration purposes only. In a real-world scenario you should include validation of the properties to ensure that a valid state is always present.

public Employee(int payrollNumber, string lastName)
{
    PayrollNumber = payrollNumber;
    LastName = lastName;
}

The new constructor replaces the default version that is currently used to create Bob Smith, our test employee. If you try to compile the program you will receive an error indicating that no constructor exists with zero arguments. To rectify the problem, you must change the assignment of the Employee object to use the new constructor. This is achieved by simply adding the correct parameters before the opening brace of the object initializer, as follows:

Employee emp = new Employee(1, "Smith")
{
    FirstName = "Bob",
    Salary = 35000,
    Holidays = 25
};

When using a custom constructor and an object initializer together, remember that the entire constructor is executed first. Once this process is completed, each of the assignments in the object initializer are processed in turn.

28 October 2008