Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I inherit IDisposable?

Tags:

Class names have been changed to protect the innocent.

If I have an interface named ISomeInterface. I also have classes that inherit the interface, FirstClass and SecondClass. FirstClass uses resources that must be disposed. SecondClass does not.

So the question is, where should I inherit from IDisposable? Both of the following options seem less than ideal:

1) Make FirstClass inherit IDisposable. Then, any code that deals with ISomeInterfaces will have to know whether or not to dispose of them. This smells like tight coupling to me.

2) Make ISomeInterface inherit IDisposable. Then, any class that inherits from it must implement IDisposable, even if there is nothing to dispose. The Dispose method would essentially be blank except for comments.

#2 seems like the correct choice to me, but I'm wondering if there are alternatives.

like image 584
Andy West Avatar asked Dec 02 '09 16:12

Andy West


People also ask

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

When should you implement IDisposable?

in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed. If not, this responsibility is left to the garbage collector to free the memory when the object containing the unmanaged resources is finalized.

What is the use of IDisposable?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.

Why is IDisposable needed in C#?

Implementing IDispose gives you a place to release resources that you "hold" like streams, handles or database-connections. Dispose() is called from the garbage collector, basically asking the object: "if there is something that you no longer need, but I can't figure out; release it now; clean up!"


1 Answers

If there is a reasonable chance that an abstract entity (interface or abstract class) might need to be disposable, it should implement it. Stream, for example doesn't itself need IDisposable, nor does IEnumerator<T>...

An abstract base class may be simpler, as you can have a default (empty) implementation of Dispose() then, and possibly the finalizer / Dispose(bool) pattern, i.e.

~BaseType() => Dispose(false);  protected virtual void Dispose(bool disposing)  { }  void IDisposable.Dispose()  {      Dispose(true); GC.SuppressFinalize(this);  } 
like image 180
Marc Gravell Avatar answered Sep 21 '22 03:09

Marc Gravell