C#, DotNet

Add item in collection with Collection Initializers


 

It is simple example to add item in generic list but sometimes it is very useful to use collection/object initializers to write less code. I am taking example to add item in generic list with or without automatic initialization of object;

Let’s say we have class employee:

  public class Emp
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }

Normal Way

List list = new List();
//object initializers
list.Add(new Emp() { Id = 1, Name = "Neeraj" });
//object initializers
list.Add(new Emp() { Id = 2, Name = "Kaushik" });

 

 

Automatic Initialization

      List list1 = new List() { 
                new Emp() { Id = 1, Name = "Neeraj" }, 
                new Emp() { Id = 2, Name = "Kaushik" } 
                };//collection initialization

 

 

You can more read about Object and Collection Initializers here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s