Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# possible mistaken empty statement

Tags:

c#

In C#, I can write something like:

using (new MyDisposableClass().MethodA());

The semicolon causes a compiler warning to be shown which states possible mistaken empty statement. I haven't run the above code but won't the method still be called?

What uses is there of this type of coding convention? I saw another thread on here about this but I ask in case there areny differences now/therefore different replies.

Thanks

like image 887
GurdeepS Avatar asked Dec 10 '22 16:12

GurdeepS


1 Answers

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(); }
like image 174
Paul Alexander Avatar answered Dec 26 '22 21:12

Paul Alexander