This was a telephone interview question I had: Is there a time when Dispose will not be called on an object who's scope is declared by a using block?
My answer was no - even if an exception happens during the using block, dispose will still be called.
The interviewer disagreed and said if using is wrapped in a try catch block then Dispose will not be called by the time you enter the catch block.
This goes contrary to my understanding of the construct and I haven't been able to find anything that backs up the interviewers point of view. Does anyone know if he's correct or maybe if I might have misunderstood the question?
void Main()
{
try
{
using(var d = new MyDisposable())
{
throw new Exception("Hello");
}
}
catch
{
"Exception catched".Dump();
}
}
class MyDisposable : IDisposable
{
public void Dispose()
{
"Disposed".Dump();
}
}
This produced :
Disposed
Exception catched
So I agree with you and not with the smarty interviewer...