Object Initializers in C# 3.0

C# 3.0 facilitates programmer by providing the feature of Object Initializers for both Named and Anonymous types. Object Initializer let you assign values to any accessible fields or properties without the need to create a explicit constructor. Consider the code below:

private class Student

    public string Name { get; set; }
    public int Age { get; set; }

static void SomeMethod()
    // Object initializer
    Student stObj= new Student {Name = “Adil”,  Age = 24 };


If we notice in the code above, the properties of student are assigned values directly with the use of braces { } around it and comma in between each member. Without object initializer this will be done in the way as shown below:

Student stObj=new Student();
stObj.Age= 24;

Again features such as Automatic properties, Implicitly typed local variables and Object Initializer are provided in C# 3.0 specially to support LINQ.