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
this code basically translates to
Basically you’re disposing the result of the call to
MethodA, rather than disposing of theMyDisposableClasswhich 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:The parser evaluates two entirely separate blocks and is seen by the compiler as if you had typed this:
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;.Note still that this is disposing the result of the call to MethodA – not the MyDisposableClass instance. Your code should actually be written as