[source lang="csharp"]
class Something : IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposed something");
}
}
class Danger : IDisposable
{
public Danger(Something something)
{
throw new InvalidOperationException();
}
~Danger()
{
Dispose();
}
public void Dispose()
{
Console.WriteLine("Disposed danger");
}
}
// Karsten_'s example class
class Test : IDisposable
{
Something something;
public Test()
{
something = new Something();
using (Danger danger = new Danger(something)) { }
}
// finalizer overload
~Test()
{
Dispose();
}
public void Dispose()
{
if (something != null)
{
something.Dispose();
something = null;
Console.WriteLine("Disposed test");
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
Test test = null;
try
{
test = new Test();
}
catch (Exception e)
{
}
}
}
[/source]
The output I get is this:
Disposed danger
Disposed something
Disposed test
It's still a bit verbose compared to the C++ version, but arguably less so than the one with the try/catch inside Test's constructor. Granted that now the disposing will happen when the GC runs, which may not always be desirable, but you never specified that the disposing must happen immediately after the exception is thrown.