Skip to content

Block Object Initializers

July 25, 2008

Nobody tells me anything.  Apparently it’s been since the 3.0 framework that one could initialize an object’s properties in block format.  Like so:

WinError error = new WinError()
            {
                applicationID = 1,
                errorText = "Foo",
                errorTimeStamp = DateTime.Now,
                handleCount = 123,
                machineName = "welcomeToThe",
                peakMemory = 1234,
                threadCount = 333,
                userName = "fooMan",
                virtualMemory = 433,
                workingMemory = 3122
            };

This is however not exactly as it appears.  A rather sharp guy named Bart De Smet explains that the declaration behind the scenes is actually an atomic assignment.  A new object is created, the assignments are attempted and then the successful temp object is assigned to the original object.

So what is really happening is more like:

WinFormError er = new WinFormError();

            er.applicationID = 1;

            er.errorText = "Foo";



WinFormError theError = er;

The main takeaway is that this makes the statement thread safe out of the box without having to do your own locking during assignment so that nothing starts accessing the object’s properties while its still being assigned.

 Edit:

A buddy of mine asked if this would work with a using block.  Yes, yes it does.

private void button3_Click(object sender, EventArgs e)

        {

            using (TestClass foo = new TestClass() { TestProp = "foo" })

            {

                MessageBox.Show(foo.TestProp);

            }

        }

        public class TestClass : IDisposable

       
{           
            public TestClass()

            {               
            }

            public void Dispose()

            {

                throw new NotImplementedException();

            }

            private string testProp;

            public string TestProp

            {

                get { return testProp; }

                set

               
{

                    testProp = value;

                }

            }

        }

It decompiles down to this as expected:

private void button3_Click(object sender, EventArgs e)
{
    TestClass <>g__initLocalc = new TestClass();
    <>g__initLocalc.TestProp = "foo";
    using (TestClass foo = <>g__initLocalc)
    {
        MessageBox.Show(foo.TestProp);
    }
}
Advertisements
No comments yet

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

%d bloggers like this: