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:
- Never use object initializers with types implementing IDisposable
- 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 ;)