I have this test code. Why is the dispose method not called when an exception is raised inside using statement? According to the documentation it should be called.
using System;
using System.IO;
using System.Text;
namespace UsingTest {
class Program {
public class MyClass : IDisposable
{
private bool disposed = false;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
using (var f = new FileStream("log.txt", FileMode.Create)) {
var msg = "MyClass disposed";
f.Write(Encoding.UTF8.GetBytes(msg), 0, Encoding.UTF8.GetByteCount(msg));
}
}
disposed = true;
}
}
~MyClass() {
Dispose(false);
}
}
static void Main(string[] args) {
using (var c = new MyClass()) {
Console.WriteLine("some work");
throw new Exception("Exception");
Console.WriteLine("Hello World!");
}
}
}
}
Thanks.