I read that Dispose method is called even if exeception is thrown from within a using block as using gets translated into try/finally clauses by compiler where (in IL) Dispose is being called in finally clause. But in my example code below, when i debug it in Visual Studio, it throws exeception and Dispose never gets called. Please let me know what's wrong here. Thanks a bunch.
Please note obj.GetType() throws exeception as I'm doing intentionally to see if Dispose gets called or not as menioned above.
class Datatbase
{
public void Commit()
{
Console.WriteLine("Commiting database transaction.");
}
public void Rollback()
{
Console.WriteLine("Rolling back transaction.");
}
}
class Helper : IDisposable
{
private bool disposed = false;
private bool commited = false;
private Datatbase db;
public Helper(Datatbase db)
{
this.db = db;
}
~Helper()
{
Dispose(false);
}
public void Commit()
{
db.Commit();
commited = true;
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// coming through dispose method.
if (!commited) db.Rollback();
}
else
{
// coming through finalizer.
Console.WriteLine("User forgot to call dispose method.");
}
}
}
}
private static void DoSomething(Datatbase db)
{
using (Helper h = new Helper(db))
{
obj.GetType();
db.Commit();
}
}
private static Object obj = null;