Object Initializer in C#



Let us play around with some new features of C# 3.0 or above and you can say .Net framework 3.0 and above, like Object initializer, implicitly typed variables, extension methods, anonymous types, object initializer, Collection initializer, and automatic properties.

Let's start with Object and collection initializes.

Just refer to the following code of style. Definitely all .Net coders are aware of these lines.

public class Customer
{
    private int _customerID;
    private string _companyName;
    private Phone _phone;
    public int CustomerID
    {
        get { return _customerID; }
        set { _customerID = value; }
    }
    public string CompanyName
    {
        get { return _companyName; }
        set { _companyName = value; }
    }
    public Phone Phone
    {
        get { return _phone; }
        set { _phone = value; }
    }
}

public class Phone
{
    private string _countryCode;
    public string CountryCode
    {
        get { return _countryCode; }
        set { _countryCode = value; }

    }
    private string _areacode;
    public string AreaCode
    {
        get { return _areacode; }
        set { _areacode = value; }
    }
    private string _phonenumber;
    public string AreaCode
    {
        get { return _phonenumber; }
        set { _phonenumber = value; }
    }

}

Regular method of initializing an instance of the Customer class.

 Phone oPhone = new Phone();
 oPhone.CountryCode = "+91";
 oPhone.AreaCode = "0999";
 oPhone.PhoneNumber = "999999";

 Customer oCustomer = new Customer();
 oCustomer.CustomerID = 101;
 oCustomer.CompanyName = "oTest Corporation";
 oCustomer.Phone = oPhone; 

By taking advantage of Object Initializers an instance of the Customer class

Customer nCustomer = new Customer()
 {
     CustomerID = 102,
     CompanyName = "nTest Corporation",
     Phone = new Phone()
     {
         CountryCode = "+91",
         AreaCode = "09999",
         PhoneNumber = "999999"
     }
 };

We do not need to take care of performance issues. Because in the execution time, both samples make sample IL code. So both samples give sample performance.

Next time we will look into automatic property.

Happy coding

Up Next
    Ebook Download
    View all
    Learn
    View all