Search code examples
c#.netidisposableusing-statementresource-management

What is the relationship between the using keyword and the IDisposable interface?


If I am using the using keyword, do I still have to implement IDisposable?


Solution

  • If you use the using statement the enclosed type must already implement IDisposable otherwise the compiler will issue an error. So consider IDisposable implementation to be a prerequisite of using.

    If you want to use the using statement on your custom class, then you must implement IDisposable for it. However this is kind of backward to do because there's no sense to do so for the sake of it. Only if you have something to dispose of like an unmanaged resource should you implement it.

    // To implement it in C#:
    class MyClass : IDisposable {
    
        // other members in you class 
    
        public void Dispose() {
            // in its simplest form, but see MSDN documentation linked above
        }
    }
    

    This enables you to:

    using (MyClass mc = new MyClass()) {
    
        // do some stuff with the instance...
        mc.DoThis();  //all fake method calls for example
        mc.DoThat();
    
    }  // Here the .Dispose method will be automatically called.
    

    Effectively that's the same as writing:

    MyClass mc = new MyClass();
    try { 
        // do some stuff with the instance...
        mc.DoThis();  //all fake method calls for example
        mc.DoThat();
    }
    finally { // always runs
        mc.Dispose();  // Manual call. 
    }