Object initializer provides a shortcut to initialize an object with property values.
Considering the following class.
public class Employee {
public Employee() {
}
public Employee(int id) {
this.ID = id;
}
public int ID { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}
With object initializer, we can initialize an Software Engineer John with ID 10, in one statement.
var e = new Employee() {
ID=10,
Name="John",
Designation="Software Engineer"
};
or
var e = new Employee(10) {
Name="John",
Designation="Software Engineer"
};
Second example shows the initialization of a class with parameterized constructor.
No comments:
Post a Comment