Click here to Skip to main content
16,021,430 members
Articles / Programming Languages / C#
Tip/Trick

Object and Collection Initialization

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
19 Dec 2010CPOL1 min read 25.6K   2   2
Object and Collection Initialization
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:
// Code size       32 (0x20)
  .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
  // Code size       34 (0x22)
  .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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralReason for my vote of 5 Excellent Pin
Member 313707816-Dec-10 3:04
Member 313707816-Dec-10 3:04 
Reason for my vote of 5
Excellent
GeneralReason for my vote of 4 Good explanation, examples. Pin
dmjm-h13-Dec-10 5:34
dmjm-h13-Dec-10 5:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.