Tigraine

Daniel Hoelbling-Inzko talks about programming

C# Object Initializers are Expressions!

Posted by Daniel Hölbling on August 14, 2010

Object initializers got introduced into C# as part of .NET 3.5 and allow you to define properties through a nice concise syntax that makes code easier to read. Here’s an example:

var daniel = new User()
                    {
                        Username = "Tigraine",
                        Age = 25,
                        Email = "[email protected]"
                    };

In a .NET 2.0 environment the above code would have looked like this:

var daniel = new User();
daniel.Username = "Tigraine";
daniel.Age = 25;
daniel.Email = "[email protected]";

The funny thing here is that the .NET 2 code is not thread safe. If daniel is a public field or static field anywhere, the scheduler could interrupt the Thread right after setting the age, leaving you with an empty email field. This is also the reason why I’d call object initializers expressions: Expressions do by definition yield a value. And if we look at the code the compiler generates for an object initializer you will see this:

User <>g__initLocal0 = new User();
<>g__initLocal0.Username = "Tigraine";
<>g__initLocal0.Age = 0x19;
<>g__initLocal0.Email = "[email protected]";
User daniel = <>g__initLocal0;


The compiler does emit code that constructs the new object in a local variable that gets discarded right afterwards, and only the completed object, with all properties initialized will then be assigned to the variable. This makes this code thread safe. But, you’ll say it doesn’t yield a result thus it’s not really an expression.

Well, rewrite it a bit and you get a expression:

Func<User> expr = () =>
                    {
                        var user = new User();
                        user.Username = "Tigraine";
                        user.Age = 25;
                        user.Email = "[email protected]";
                        return user;
                    };
var daniel = expr();


It’s essentially a function that the compiler generates inline to save the cost of a method call, but it’s semantically a function, thus it yields a value and is a expression.

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more