As mentioned above, only the first method will catch exceptions in the IDisposable object's initialization, and will have the object in-scope for the catch block.
In addition, the order of operations for the catch and finally blocks will be flipped depending on their nesting. Take the following example:
public class MyDisposable : IDisposable
{
public void Dispose()
{
Console.WriteLine("In Dispose");
}
public static void MethodOne()
{
Console.WriteLine("Method One");
using (MyDisposable disposable = new MyDisposable())
{
try
{
throw new Exception();
}
catch (Exception ex)
{
Console.WriteLine("In catch");
}
}
}
public static void MethodTwo()
{
Console.WriteLine("Method Two");
try
{
using (MyDisposable disposable = new MyDisposable())
{
throw new Exception();
}
}
catch (Exception ex)
{
Console.WriteLine("In catch");
}
}
public static void Main()
{
MethodOne();
MethodTwo();
}
}
This will print:
Method One
In catch
In Dispose
Method Two
In Dispose
In catch