15 January 2012

Object Initializers in C#


Hi all, finally i am back after long time.

Today we are going talk about Object Initializers ,

Now what exactly Object Initializer is ,
It's a C# 3.0 feature,
using which we can create object of a class and assign values to any accessible fields or properties of it  at the same time, its not required explicitly invoke a constructor.

Lots of times, we create object of a class and start immediately setting values to its properties,

Lets take an example.
public class Car
{
 public string Name{get;set;}
 public Color Color{get;set;}
}
In C# 2.0 we write following code to create instance of Car and for setting it's properties.
Car myCar=new  Car ();
myCar.Name ="Chevrolet Corvette";
myCar.Color =Color.Red;
//OR Even with lots of controls it happens
TextBoxt t=new TextBox();
t.Id="txtCustomerName";
t.CssClass="textbox";
C# 3.0 make it easy with the help of Object Initializers
Car myCar=new Car(){Name="Chevrolet Corvette",Color=Color.Red};
Its simple,compact and easy to use, normally if u have worked with JSON you could have seen such syntax,

Basically this kind of feature saves some typing and code will become more concise.

Hope you enjoyed, Stay tuned for more, till then Enjoy Programming.