this code basically translates to
MyDisposableClass tmp = new MyDisposableClass().MethodA(); try { } finally { if( tmp != null ) tmp.Dispose(); }
Basically you delete the result of calling MethodA , and not delete MyDisposableClass , which is the likely intent.
; following the instructions for use is legal, but a warning indicates that you may have added it there by mistake. For example, the following code will not compile:
using( var tmp = new MyDisposableClass() ); { tmp.MethodA(); }
The parser evaluates two completely separate blocks and is considered by the compiler as if you typed this:
using( var tmp = new MyDispoableClass() ) { } { tmp.MethodA(); }
Easy to miss saggy ; eye, so a compiler warning just suggests that you probably wanted to do something else. There are times when shorter compression is required, and I think the best way to indicate that it is on purpose is to use {} instead ; .
using( new MyDisposableClass().MethodA() ){}
Note that this deletion of the result of the MethodA method is not an instance of MyDisposableClass. Your code should be written as
using( var tmp = new MyDisposableClass() ){ tmp.MethodA(); }
source share