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

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

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

7条回答
  •  情书的邮戳
    2020-12-10 19:04

    Using will only dispose of disposable objects. So wraping a using block around an object that does not implement IDisposable is rather useless will in fact cause a compiler error.

    http://msdn.microsoft.com/en-us/library/yh598w02.aspx

    As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

    The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

提交回复
热议问题