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

后端 未结 7 516
栀梦
栀梦 2020-12-10 18:38

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

相关标签:
7条回答
  • 2020-12-10 19:06

    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.

    0 讨论(0)
提交回复
热议问题