The documentation says
You should implement IDisposable only if your type uses unmanaged resources directly.
Coming from a mostly Java background, this sounds strange to me. Suppose I have a class that contains an IDisposable member:
class Foo : IDisposable {
private StreamWriter sw;
...
}
... and suppose this class is used, for example, as a sort of filter that takes strings and modifies them and then outputs them with the StreamWriter sw
. I want to use this class like a sort of Writer.
Why wouldn't I want to implement Dispose(bool)
which would call sr.Dispose()?
This is what I would have to do if I were coding it in Java (the Java Closable
interface is similar to .NET's IDisposable
, though in some ways different). Yet the documentation says I shouldn't, because I'm not directly using unmanaged resources.
If I don't override Dispose(bool)
, how does the managed resource sw
get disposed when I leave the block started by the using
statement?
You should implement IDisposable
when your class contains an IDisposable
field such as for example a StreamWriter
.
In this case you can assume that your type does use unmanaged resources (through the StreamWriter
class) under the hood, and you should always dispose any object that implements the IDisposable
interface as soon as you are done using them.
Why wouldn't I want to implement
IDisposable(bool)
which would callsr.Dispose()
?
You certainly would.
If I don't override
Dispose(bool)
, how does the managed resourcesw
get disposed when I leave the block started by theusing
statement?
It doesn't. The underlying unmanaged resource(s) may eventually be released by the finalizer (depending on the implementation of the IDisposable
class) but the managed object won't be disposed unless you explicitly dispose it in your class.
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