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.

4 comments:

  1. Thank you for the post, it was really a good one for those who re beginning with C# coding.

    Can you do one array initializers??

    ReplyDelete
  2. Good one..keep posting regularly.

    ReplyDelete

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...