Archive

Posts Tagged ‘Object Initializers’

C# 3.0 Object Initializers Tutorial

October 4th, 2011 No comments
It was introduced in C# 3.0. Object Initializers allows you to create default values for newly created object along with their type. Now you can easily assign data to specific properties.  In traditional way the following example creates a Book object and passes two values to its constructor.
publicclassBook
{
   int bookno, bookprice;
   public  Book(int _bp, int _pn)
   {
       //code
   }   //setters/getters code will goes here
}

Once you start using this class, you will create the object with default parameters, but you don’t’ have the clear idea about the parameters.  In other words in below line you cannot find which values belongs to which properties. You don’t have the clear idea about parameters and values.
Book objBook = newBook(200, 100);

C# new feature Object Initializers solve this problem and you can save your time a bit, you can easily assign or specify the data to the specific property as

publicclassBook
{
   int bookno, bookprice;

       //setters/getters
   publicint Booknumber { get; set; }
   publicint PageNo { get; set; }

}

Book objBook = newBook(BookPrice = 100, PageNo = 2);

In above line you can directly assign values to both properties “BookPrice” & “PageNo”. From the developer point’s it is really good and more clear now. I can say it gives a clear picture to your class however sometime it creates some confusion when developer leave this choice on user, user might get confused to choose the essentials properties of the system.