As Damien points out in the comments, the FxCop warning is valid, since the C# compiler creates the IDisposable
instance in a hidden temp
variable, and when an exception is thrown during the initialization of one of the properties that instance will not get disposed.
With a good API design this would not be a problem, since resources (things that implement IDisposable
) should contain an Open
(or Begin
, Start
, whatever) method (according to the Framework Design Guidelines), and should not leak before Open
is called. This rule is created for the same reason as what you are experiencing: to prevent leaking during initialization. The FDG were written before C# 3.0, but the same problem exists when the an exception is thrown from within the constructor of that instance (which can always happen because of asynchronous exceptions such as thread aborts). Since the reference to the instance isn't published at that point, there is no way for anyone to dispose that instance. Initializing the underlying resources during construction is therefore not advised.
So you can safely discard that warning when Myclass
contains some sort of Open
method, and when you're not initializing it with values that implement IDisposable
themselves. In other cases, you should revert to the following:
var myclass = new MyClass();
try
{
myclass.Name = "a name";
}
finally
{
myclass.Dispose();
}