views:

481

answers:

5

EDIT: This question is a duplicate of What is the difference between managed and native resources when disposing? (.NET) and many others. Please answer the others if you have something to add.


According to the Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams, a type that contains instances of disposable types should implement IDisposable.

Is there any other general rule of thumb for when it is best practice to implement IDisposable?

+4  A: 

When you need to release unmanaged resources, implement IDispoable.

Jason
You should also implement IDisposable if your class has fields that implement IDisposable
Philippe Leybaert
The initial question states "is there any other general rule of thumb for when it is best practice to implement IDispoable" in addition to the rule that a type containing instances of disposable types should implement IDisposable.
Jason
Further, if you have instances of objects that implement IDispoable, then you have unmanaged resources that need to be released and thus it falls under the rule I stated.
Jason
+1  A: 

From MSDN: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

Ian Davis
+1  A: 

Whenever you alocate resources that must be released, such as files, handles, etc. For example, if you are using Win32 resources (which do not implement IDisposable) you should implement IDisposable to release them.

Otávio Décio
A: 

I normally implement IDisposable every time I need to do a clean up of items. For me this is when writing code that abstracts database/network/filesystems.

It just marks items ready for the Garbage Collector instead of waiting for it to try do it on its own.

AutomatedTester
+2  A: 

Implement IDisposable when you have a class what wraps an unmanaged resource or when your class has a field that implements IDisposable.

ddc0660