Object Initializer in C# 3.0
Object initializer is one of the new feature in C# 3.0 for easy initialization.I will explain this new feature with a simple example so that it can be easily understood.
Consider a Student Entity like,
class Student
{
public string FirstName;
public string LastName;
public int Age;
public string City;
}
If we want to initialize this entity either we will be doing it after 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
{
public string FirstName;
public string LastName;
public int Age;
public 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 simplified further and we can do it like,
Student stu=new Student(FirstName="Satheesh",
LastName="Babu",
Age=26,
City="Bangalore");
Likewise,if a member is a entity instead of primitive datatype still we can initialize it like,
class DateOfBirth
{
public int Day;
public int Month;
public int Year;
}
class Student
{
public string FirstName;
public string LastName;
public int Age;
public string City;
public DateOfBirth dob;
}
Student stu=new Student(FirstName="Satheesh",
LastName="Babu",
dob=new DateOfBirth(Day=11,Month=8,Year=1981);
Age=26,
City="Bangalore");
Object initializer is one of the new feature in C# 3.0 for easy initialization.I will explain this new feature with a simple example so that it can be easily understood.
Consider a Student Entity like,
class Student
{
public string FirstName;
public string LastName;
public int Age;
public string City;
}
If we want to initialize this entity either we will be doing it after 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
{
public string FirstName;
public string LastName;
public int Age;
public 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 simplified further and we can do it like,
Student stu=new Student(FirstName="Satheesh",
LastName="Babu",
Age=26,
City="Bangalore");
Likewise,if a member is a entity instead of primitive datatype still we can initialize it like,
class DateOfBirth
{
public int Day;
public int Month;
public int Year;
}
class Student
{
public string FirstName;
public string LastName;
public int Age;
public string City;
public DateOfBirth dob;
}
Student stu=new Student(FirstName="Satheesh",
LastName="Babu",
dob=new DateOfBirth(Day=11,Month=8,Year=1981);
Age=26,
City="Bangalore");



0 Comments:
Post a Comment
<< Home