Object Initializers in C# 3.0 and VB9

Sun, February 18, 2007, 06:36 PM under dotNET | Orcas | LINQ
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;
..or in VB if you prefer
    Dim myThread As New Thread(AddressOf MyThreadMethod)
myThread.Name = "my thread"
myThread.IsBackground = True
With object initialisers, you can combine the first 3 statements into one like so:
Thread myThread = new Thread(MyThreadMethod) {Name="my thread", IsBackground=true};
In VB:
Dim myThread As New Thread(AddressOf MyThreadMethod) With {.Name = "my thread", .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)};
In VB:
Dim t As New TextBox With {.Text = "Hi", .Multiline = True, .Location = New Point(5, 5), .Size = New Size(50, 100)}
...the compiler generates IL similar to if you typed:
      TextBox t = new TextBox(); 
t.Text = "Hi";
t.Multiline = true;
t.Location = new Point(5, 5);
t.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.