Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Object Initializers – Thread safety June 19, 2008

Filed under: C# — ppetrov @ 6:09 pm
Tags: , ,

One of the new features in C# 3.0 is object initializers. They greatly simplify the creation of new objects.

In C# 2.0 we have to say:

Person p = new Person();
p.Name = "Petar Petrov";
p.Age = 25;

Now in C# 3.0 we have

Person p = new Person() {Name = "Petar Petrov", Age = 25};

It’s simple and easy to use.
However there is one subtle difference between these two snippets.
In multithreaded environment if we use the first version of the code it’s possible to have partially initialized Person object, if the thread is interrupted between the Person’s constructor and setting the name or the age of the Person. In this case we will end up with a Person with no Age.

If we use the object initializers this situation isn’t possible. For the C# 3.0 version of the snippet the compiler generates the following code

Person p = null;
Person __p = new Person();
__p.Name = "Petar Petrov";
__p.Age = 25;
p = __p;

It’s obvious that whenever the thread is interrupted we can’t end up with partially initialized Person. The two possible options are :

p = null;


p = __p;

where __p is fully initialized Person.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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