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