C# 3.0 Enhancements: Object Initializers

C# 3.0 allows us to initialize object in far better way in one single line. Let’s talk with an example here. Back again to my favorite Customer object.

 

publicclassCustomer

{

public Customer() { }

privateint _ID;

publicint ID

    {

get { return _ID; }

set { _ID = value ; }

    }

privatestring _Name;

publicstring Name

    {

get { return _Name; }

set { _Name = value ; }

    }

}

If you want to initialize the properties with the object initialization current style won’t allow you to do so. What you can do is that you can create another public parameterized constructor, like

 

public Customer( int intCustID, string sCustName)

{

    _ID = intCustID;

    _Name = sCustName;

}

 

Now internally this will initialize the property. But you may not require to set values to property every time. C# 3.0 rescues us where we can initialize the Customer class with property even though there is just a default public constructor.

 

 

Customer objCust = newCustomer () {ID = 1,Name = "Wriju" };

 

Now if you do not want to set all the properties you can freely chose one or any number. It does not force you to initialize all the properties every time.

Customer objCust = newCustomer { Name = "Wriju" };

 

Amazing feature.

 

Namoskar!!!