Search code examples
c#.netidisposableusingfinalize

Catastrophic failures within a "using" statement i.e. using(var a= new stream()) and a.Something() throws an exception


So I understand that at the end of a using block statement, the dispose method is called.

What happens if I use a 'using(var a = new Stream()) { a.SomethingThrowsAnException() }'

Does the stream just still go through he dispose method?

I wrote a class that implements IDisposable, and it is mission critical I do not lose what's in memory, so I was planning on serializing the data if something catastrophic happens i.e. I have a custom stream like object I am using.

Any suggestions?

Thanks.


Solution

  • Yes. The using block compiles down to this:

    var a = new Stream();
    try
    {
         a.SomethingThrowsAnException();
    }
    finally
    {
         a.Dispose();
    }