New Language feature in C # 3.0 Object Initializer

Hi

Another of the new language feature in the C sharp 3.0 is the object Initializer. Types within the .NET Framework rely heavily on the use of properties.  When instantiating and using new classes, it is very common to write code like below.

   Employee  employee = new Employee();
   employee.FirstName = "Vikram";
   employee.LastName = "Lakhotia";
   employee.Age = 24;

I know we can also create a constructor and pass the value as the parameters. But lets say we do not have any constructor.

With C# 3.0 the above code can be simplified an written like this.

Employee employee = new Employee { FirstName="Vikram", 
                                                                 LastName="Lakhotia", 
                                                                 Age=24 };

The compiler will generate appropriate property setter code automatically. And the code will have same meaning as the previous code snippets.

The object initializer feature allows us to optionally set more complex nested property types. Like if we have a property called PhoneNo of type PhoneNo then we can also initialize the property of PhoneNo.

Employee employee = new Employee { 

FirstName="Vikram", 

LastName="Lakhotia", 

Age=24 

phoneno = New PhoneNo { PhoneType = “Mobile”,

 Pnumber = “1111111111”;}

};

Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 5/17/2007 11:55:00 PM

Hi Vikram,

The concepts wht you explained is good. But problem is if you started to describe one topic means you should give complete description on the topic. for example if you observe this site"http://swapsnet.spaces.live.com/", in this she posted about assemblies. She gave all the information on assemblies, like that if you give on oops it wil be great. don;t feel if i hurt you.

Posted on 5/18/2007 7:18:01 AM

Hi Nagesh

I try and keep small snippet of all the things and slowly and steadely go deep in the topics. This post was one the posts on the new feature of C Sharp 3.0. Covering all the new feature in one post will be difficult so I am using different posts.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia