DarioSantarelli.Blog(this);

C# 3.0: Object Initializers

Posted by dariosantarelli on July 20, 2007

 In C# 3.0, creating an object instance and initializing it is now possible by using the new “object initializers” . Here an example:

class Contact 
{ 
 public string Name; 
 public readonly Location location = new Location(); 
} 

... 

Contact myContact = new Contact 
{ 
  Name = "Dario", 
  Location = { Address="myAddress", City = "MyCity" } 
}; 

P.S.: This feature is NOT available in VB9 because it doesn’t support read-only properties/fields initialization.

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

 
%d bloggers like this: