C# 3.0 - Object Initializers

Posted Monday, April 30, 2007 1:56 PM by C-Dog's .NET Tip of the Day

I really like this new feature in C# 3.0. It allows you to create an object and initialize its public properties all in one line of code (and the syntax still looks fairly clean). You simply add a set of brackets and list out the properties you want to assign along with a value. Here is an example (taken directly from the C# 3.0 language specificiation.)

The following class represents a point with two coordinates:

public class Point
{
int x, y;
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
}

An instance of Point can be created an initialized as follows:

var a = new Point { X = 0, Y = 1 };

which has the same effect as

var a = new Point();
a.X = 0;
a.Y = 1;

As you can see its an easy way to quickly initialize a class. Probably not ideal if you are assigning a ton of properties, but works great for simple assignments like the one above.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=351