inforakesha

A fine WordPress.com site

Collection Initializers

Leave a comment

Object Initializers are great, and make it much easier to concisely add objects to collections.  For example, if I wanted to add three people to a generics-based List collection of type “Person”, I could write the below code:

 

  List<Person> people = new List<Person>();
            
  
people.Add( new Person { FirstName “Scott”, LastName “Guthrie”, Age 32 } );
  
people.Add( new Person { FirstName “Bill”, LastName “Gates”, Age 50 } );
  
people.Add( new Person { FirstName “Susanne”, LastName “Guthrie”, Age 32 } );
 

 

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I’d need to type with the C# 2.0 compiler.

The C# and VB “Orcas” compilers allow us to go even further, though, and also now support “collection initializers” that allow us to avoid having multiple Add statements, and save even further keystrokes:

 

   List<Person> people = new List<Person> {
      
new Person { FirstName “Scott”, LastName “Guthrie”, Age 32 },
      
new Person { FirstName “Bill”, LastName “Gates”, Age 50 },
      
new Person { FirstName “Susanne”, LastName “Guthrie”, Age 32 }
   }
;

 

When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s