Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
Troy Avatar asked Aug 23 '10 04:08

Troy


3 Answers

You can't have one without the other.

When you write :

using(MyClass myObj = new MyClass())
{
    myObj.SomeMthod(...);
}

Compiler will generate something like this :

MyClass myObj = null;
try
{
    myObj = new MyClass();
    myObj.SomeMthod(...);
}
finally
{
    if(myObj != null)
    {
        ((IDisposable)myObj).Dispose();
    }
} 

So as you can see while having using keyword it is assumed/required that IDisposable is implemented.

like image 139
Incognito Avatar answered Oct 23 '22 01:10

Incognito


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. 
}
like image 25
John K Avatar answered Oct 23 '22 01:10

John K


You are confusing things. You can only use the "using" keyword on something that implements IDisposable.

Edit: If you use the using keyword, you don't have to explicity invoke Dispose, it will be called automatically at the end of the using block. Others have already posted examples of how the using statement is translated into a try - finally statement, with Dispose invoked within the finally block.

like image 34
Richard Anthony Freeman-Hein Avatar answered Oct 23 '22 01:10

Richard Anthony Freeman-Hein