Object initializers is one of the most important feature of C # 3.0.
What is Object initializers?
Using Object initializers we can initialize a object of that type without explicitly invoking the constructor of that particular type.
Object initializers:
I will explain this with a piece of code:
class Student
{
public string Name { get; set; }
public string phone{ get; set; }
public string city{ get; set; }
}
Now see the differences:
In C#2.0 we were doing like this:
Student objStudent = new Student();
objStudent.Name = “Chevrolet Corvette”;
objStudent.phone = “45345345”;
objStudent.city= “New Delhi”;
But in C# 3.0 we can use the same thing like this:
Student objStudent = new Student { Name = “Jhon”, phone = “4543432”, city = “New Delhi” };
This is because of object initializers feature of C# 3.0.
Now we will see Collection Initializers:
In C# 3.0 we can do the collection initializers by below code:
List<Student> listStudent = new List<Student>()
{
new Student { Name = “John”, city=”New Delhi”, phone=”24234234″},
new Student { Name = “Tom”, city=”Mumbai”, phone=”5464564″},
new Student { Name = “Steve”, city=”Bangalore”, phone=”56756756″},
};
Thanks to C# 3.0 object initializers.