If I am using the using
keyword, do I still have to implement IDisposable
?
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.
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.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With