using (IDisposable disp = new IDisposable()) {
This code will be translated as follows:
IDisposable disp = new IDisposable(); try { //some logic here } finally { if (disp != null) ((IDisposable)disp).Dispose(); }
The code in the finally block is always executed, so it gives you the ability to throw exceptions, returning from using the block without any doubt that Dispose will not be called.
But you have to be careful with using initializers and objects.
using (var fs = new FileStream(@"C:\blabla", FileMode.Open) { Position = pos }) {
As you can see from here, the Position property can throw exceptions. And the problem is that the object will be created, and it will be made from a try block , so a memory leak may occur. Right way to that
using (var fs = new FileStream(@"C:\blabla", FileMode.Open)) { fs.Position = pos;
source share