Is there a situation in which Dispose won't be called for a 'using' block?
Four things that will cause Dispose to not be called in a using block:
- A power failure on your machine when inside the using block.
- Your machine getting melted by an atomic bomb while in the inside of the using block.
- Uncatchable exceptions like
StackOverflowException
,AccessViolationException
and possibly others. - Environment.FailFast
void Main()
{
try
{
using(var d = new MyDisposable())
{
throw new Exception("Hello");
}
}
catch
{
"Exception caught.".Dump();
}
}
class MyDisposable : IDisposable
{
public void Dispose()
{
"Disposed".Dump();
}
}
This produced :
Disposed
Exception caught
So I agree with you and not with the smarty interviewer...
Bizarrely I read about a circumstance where Dispose won't get called in a using block just this morning. Checkout this blog on MSDN. It's around using Dispose with IEnumerable and the yield keyword, when you don't iterate the entire collection.
Unfortunately this doesn't deal with the exception case, honestly I'm not sure about that one. I would have expected it to be done but maybe it's worth checking with a quick bit of code?