Movatterモバイル変換


[0]ホーム

URL:


The MothMy Photo - click to enlarge

Developer, Former MVP, now at Microsoft - Best of2004,2005,2006,2007,2008,2009,2010,2011,2012,2013

« Option Infer in VB9 | Anonymous Types in C# 3.0 and VB9 »

Object Initializers in C# 3.0 and VB9

Sun, February 18, 2007, 06:36 PM underdotNET | Orcas | LINQ
How many times have you created an object and immediately started setting properties on it? For example, wherever I create aThreadobject 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.
Comments [0] |#Permalink

© Copyright 2004-2025, Daniel Moth -Disclaimer
Powered by newtelligence dasBlog 2.3.9074.18820
Page rendered Friday, 18 July 2025 14:29:48 (Pacific Daylight Time, UTC-07:00)


About
Tags
Latest Posts
Archives

[8]ページ先頭

©2009-2025 Movatter.jp