this code basically translates to
MyDisposableClass tmp = new MyDisposableClass().MethodA();
try
{
}
finally
{
if( tmp != null )
tmp.Dispose();
}
Basically you're disposing the result of the call to MethodA
, rather than disposing of the MyDisposableClass
which is the likely intent.
The ;
following the using statement is legal but the warning suggests that you might have added it there by mistake. For example the following code won't compile:
using( var tmp = new MyDisposableClass() );
{
tmp.MethodA();
}
The parser evaluates two entirely separate blocks and is seen by the compiler as if you had typed this:
using( var tmp = new MyDispoableClass() )
{
}
{
tmp.MethodA();
}
It's easy to miss a dangling ;
by eye so the compiler warning is simply suggesting that you probably meant to do something else. There are times when the shorter concise statement is desired and I think the best way to indicate that it is on purpose is to use {}
instead of a ;
.
using( new MyDisposableClass().MethodA() ){}
Note still that this is disposing the result of the call to MethodA - not the MyDisposableClass instance. Your code should actually be written as
using( var tmp = new MyDisposableClass() ){ tmp.MethodA(); }