inforakesha

A fine WordPress.com site

Object Initializers in C# 3.0

Leave a comment

How many times have you created an object and immediately started setting properties on it? For example, wherever I create a Thread object I use the following almost boilerplate snippet:

Thread myThread = new Thread(MyThreadMethod);
myThread.Name = "my thread";
myThread.IsBackground = true;
So, object initialisers is a feature that lets you assign public properties (and public fields) straight after the constructor in braces, without having to repeat the object variable name and type separate statements.

Note that the compiler generates the long hand code. For example, when you type the following statement:
TextBox t = new TextBox {Text="Hi", Multiline=true, Location = new Point(5,5), Size=new Size(50,100)};

This feature saves you some typing and results in more concise code. While I like object initialisers, their full usefulness will become apparent when combined with the language enhancement that we look at next.
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 )

Connecting to %s