inforakesha

A fine WordPress.com site

Object Initializers

Leave a comment

Types within the .NET Framework rely heavily on the use of properties.  When instantiating and using new classes, it is very common to write code like below:

 

   Person person = new Person();
   
person.FirstName “Scott”;
   
person.LastName “Guthrie”;
   
person.Age 32;

 

Have you ever wanted to make this more concise (and maybe fit on one line)?  With the C# and VB “Orcas” compilers you can now take advantage of a great “syntactic sugar” language feature called “object Initializers” that allows you to-do this and re-write the above code like so:

 

  Person person = new Person { FirstName=“Scott”, LastName=“Guthrie”, Age=32 };

 

The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.

In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types.  For example, assume each Person type we defined above also has a property called “Address” of type “Address”.  We could then write the below code to create a new “Person” object and set its properties like so:

 

   Person person = new Person {
      FirstName 
“Scott”,
      LastName 
“Guthrie”
      
Age 32,
      Address 
= new Address {
         Street 
“One Microsoft Way”,
         City 
“Redmond”,
         State 
“WA”,
         Zip 
98052
      
}
   }
;
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