Friday, April 15, 2011

ReSharper's Object Initializer Quick Fix and IDisposable

This week I had to realize that not every Resharper suggestion is really useful. Some quick fixes carelessly applied can even introduce flaws into your code. The quick fix I have in mind is Resharpers suggestion to use an object initializer instead of creating an instance with subsequent assignments to its properties. Applying this quick fix to following code:
var person = new Person();
person.Name = "John";
person.Lastname = "Doe";
would change it to:
ver person = new Person {
     Name = "John", Lastname = "Doe" };
This quick fix is really handy and can imho improve the readability of the code. But it should not be applied when the type is an IDisposable! Why? An object initializer just creates a temporary instance of Person initializes the properties and then assignes this temporary variable to the variable person. Something like that:
var temp = new Person();
temp.Name = "John";
temp.Lastname = "Doe";
var person = temp;
The problem is that if an exception is thrown during the properties initialization you have no chance to dispose the new instance because you have no access to that temporary local variable. It's created by the compiler and is therefore not visible in you c# code. Even if you put the object initializer inside a try catch block or an using directive you will have a problem: http://ayende.com/Blog/archive/2009/01/15/avoid-object-initializers-amp-the-using-statement.aspx.

Things learned:

  1. Never use object initializers with types implementing IDisposable
  2. Resharper is a great tool but you should never apply quick fixes blindly. Think for yourself. Don't let the tools do the thinking for you ;)