Object Initializer

.NET gives us a few handy shortcuts that help us code faster and cleaner! One of them is the Object Initializer. Each time you create a class that you intend to instantiate, you don’t need to create a constructor for them. The CLR silently creates a default constructor. What makes it cool is that they also allow you to treat your properties as is they are part of the constructor

So instead of saying

var initialMessage = new CustomMessage();

initialMessage.Message = "Connection Established";

 

You can just say

var initialMessage = new CustomMessage

{Message = "Connection Established"};

 

And then you can access all of the exposed properties available. You don’t need  to create a separate constructor unless your want to do specific things with a specific set of parameters

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