Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you implement IDisposable to clean up unmanaged resources only?

Tags:

c#

.net

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?

like image 799
DodgyCodeException Avatar asked Mar 06 '23 20:03

DodgyCodeException


1 Answers

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 call sr.Dispose()?

You certainly would.

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?

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.

like image 186
mm8 Avatar answered Apr 28 '23 05:04

mm8