Wriju's BLOG

.NET, Cloud and everything

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.


public class Customer


    public Customer() { }


    private int _ID;

    public int ID


        get { return _ID; }

        set { _ID = value; }



    private string _Name;

    public string 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 = new Customer() {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 = new Customer { Name = “Wriju” };


Amazing feature.