CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

New Object Initializer in C# 3.0
Submitted By Satheesh Babu B
On 11/8/2008 5:20:45 AM
Tags: C#,CodeDigest  

Object initializer is one of the new features in C# 3.0 for easy initialization. We will understand this simple feature with examples.

 

Consider a Student Entity like,

 

class Student

{

private string FirstName;

private string LastName;

private int Age;

private string City;

}

 

Traditionally, we will initialize this entity either by instantiating or in the constructor like,

 

Student stu=new Student();

stu.FirstName="Satheesh";

stu.LastName="Babu";

stu.Age=26;

stu.City="Bangalore";

 

OR

 

class Student

{

private string FirstName;

private string LastName;

private int Age;

private string City;

public Student(string _fname,string _lname,int _age,string _city)

{

FirstName=_fname;

LastName=_lname;

Age=_age;

City=_city;

}

}

 

Student stu=new Student("Satheesh","Babu",26,"Bangalore");

 

In C# 3.0, this is still simplified and we can do it like,

 

Student stu=new Student(FirstName="Satheesh",

                        LastName="Babu",

                        Age=26,

                        City="Bangalore");

 

Likewise, if a member is another object it can be still initialized like,

 

 

Student stu=new Student(FirstName="Satheesh",

                        LastName="Babu",

                        dob=new DateOfBirth(Day=11,Month=8,Year=1981);

                        Age=26,

                        City="Bangalore");  

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..