Showing posts with label resharper. Show all posts
Showing posts with label resharper. Show all posts

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 ;)

Tuesday, March 8, 2011

ReSharper: remove unused references.

Today I was cleaning up unused references in a Visual Studio solution. Thanks to ReSharper it was not as tedious as I fought at first. Another great feature provided by this tool saved me a couple of minutes (or maybe hours):  http://www.jetbrains.com/resharper/features/navigation_search.html#Find_ReferencedDependent_Code.
To use it select the referenced assembly in the solution browser and choose "Find Code Dependent on Module" from the context menu. If the assembly isn't used anywhere in the current project ReSharper will show a message box saying: "Code dependent on module XXXXXXX was not found". In this case you can remove this reference safely.