What is object Initialization?
Object initialization is a new feature in C#3.0 which allows to create object without writing too much lengthy code and without invoking the constructor.
Example:
class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public Employee(){}
public Employee (string name) { Name= name; }
}
To define object without object Inialization, then your code is like:
Employee emp = new Employee();
emp.Name="pranay";
emp.Address = "Ahmedabad";
or
Employee emp = new Employee("Krunal");
emp.Address = "Ahmedabad";
IL Code for this in ILDASM:
.maxstack 2
.locals init ([0] class anonymoustype.Employee emp)
IL_0000: nop
IL_0001: newobj instance void anonymoustype.Employee::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldstr "pranay"
IL_000d: callvirt instance void anonymoustype.Employee::set_Name(string)
IL_0012: nop
IL_0013: ldloc.0
IL_0014: ldstr "Ahmedabad"
IL_0019: callvirt instance void anonymoustype.Employee::set_Address(string)
IL_001e: nop
IL_001f: ret
But with the object Initialization, it's like:
Employee emp = new Employee{ Name="Pranay", Address="Ahmedabad" };
or
Employee emp = new Employee() { Name="Pranay", Address="Ahmedabad" };
or
Employee emp = new Employee("Hemang") { Address="Ahmedabad" };
The thing is that all above lines of code create object of
Employee
. But the first one creates
Object
without calling constructor explicitly but it calls parameterless constructor whereas the other two call respective constructor explicitly.
IL Code for this in ILDASM for the first statement is:
.entrypoint
.maxstack 2
.locals init ([0] class anonymoustype.Employee emp,
[1] class anonymoustype.Employee '<>g__initLocal0')
IL_0000: nop
IL_0001: newobj instance void anonymoustype.Employee::.ctor()
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldstr "Pranay"
IL_000d: callvirt instance void anonymoustype.Employee::set_Name(string)
IL_0012: nop
IL_0013: ldloc.1
IL_0014: ldstr "Ahmedabad"
IL_0019: callvirt instance void anonymoustype.Employee::set_Address(string)
IL_001e: nop
IL_001f: ldloc.1
IL_0020: stloc
As you can see, the Object Initialization code is similar to the above IL code. But the thing is that the parameterless constructor gets generated by compiler which I have not written in the first statement.
Why object Initialization is part of C#3.0?
Again this new feature is part of C#3.0 to support LINQ. You can see this feature with
Anonymous type here.
Collection Initialization
Collection Initialization allows to create a collection of object using Object Initialization feature.
Example:
List<Employee> emp = new List<Employee>
{
new Employee { Name="Pranay", Address="Ahmedabad" },
new Employee { Name="Krunal", Address="Mevada" },
null
};
Summary
Object Initialization allows to create objects in one line, i.e., just one expression. So we can create a large collection of objects without writing too lengthy code which we can see in Collection Initialization.