Using Statement with an “expression”
Reading More Effective C# book, I was amazed to find out that the using statement can be used simply with an expression:
using ( resource-acquisition ) embedded-statement
If the resource-acquisition is an expression, the variable resulting from the expression will be inaccessible to the embedded-statement.
Now, the reason why this is outlined in Bill Wagner’s book is when you write generic classes. Simply put, if expression is something like “a as IDisposable”, if a actually implements IDisposable, it will be disposed after the using statement. If it does not implements IDisposable, nothing will happen.
The beauty of this is that you don’t have to know, it will work in all cases.
I didn’t know that, and I find it very neat!
blog comments powered by Disqus