Search code examples
c#idisposableusing-statement

Handling IDisposable object without the using statement


I'm sure this is an easy question, but what am I supposed to do when handling an IDisposable object without the using statement?


Solution

  • All the using construct does is call on Dispose() which IDisposable mandates you implement.

    So you can just call it yourself, instead of:

    using (IDisposable something = new SomeDisposableClass()) {
        ...
    }
    

    Do:

    IDisposable something = new SomeDisposableClass();
    
    try {
       ...
    } finally {    
       something?.Dispose();
    }
    

    Notice the use of the try..finally which will ensure Dispose() is called even if there is an exception.