apoorv020
apoorv020

Reputation: 5650

How to find all Classes implementing IDisposable?

I am working on a large project, and one of my tasks is to remove possible memory leaks. In my code, I have noticed several IDisposable items not being disposed of, and have fixed that. However, that leads me to a more basic question, how do I find all classes used in my project that implement IDisposable? (Not custom-created classes but standard Library classes that have been used).
I have already found one less-than-obvious class that implements IDisposable ( DataTable implements MarshalByValueComponent, which inherits IDisposable). Right now, I am manually checking any suspected classes by using MSDN, but isn't there some way through which I can automate this process?

Upvotes: 18

Views: 5940

Answers (5)

this. __curious_geek
this. __curious_geek

Reputation: 43207

try this LINQ query:

var allIdisposibles = from Type t in Assembly.GetExecutingAssembly().GetTypes()
                      where t.GetInterface(typeof(IDisposable).FullName) != null && t.IsClass
                      select t;

Upvotes: 0

Jehof
Jehof

Reputation: 35544

You can use NDepend to analyze your project and find all types that implement IDisposable.

Here´s the the cql query for the result

SELECT TYPES WHERE Implement "System.IDisposable"

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292425

Reflector can show you which classes implement IDisposable : just locate the IDisposable interface in Reflector, and expand the "Derived types" node

Another option, from code, is to scan all loaded assemblies for types implementing IDisposable :

var disposableTypes =
    from a in AppDomain.CurrentDomain.GetAssemblies()
    from t in a.GetTypes()
    where typeof(IDisposable).IsAssignableFrom(t)
    select t;

Upvotes: 22

Alex F
Alex F

Reputation: 43311

Test your project with FxCop. It can catch all places where IDisposable objects are not disposed. You may need to do some work to disable all irrelevant FxCop rules, leaving only IDisposable-related rules.

For example, this is one of FxCop IDisposable rules: http://msdn.microsoft.com/en-us/library/ms182289%28VS.100%29.aspx

Note: you need to find both your own, .NET and third-party IDisposable objects which are not handled correctly.

Upvotes: 8

Hans Olsson
Hans Olsson

Reputation: 55009

I think something like the code below might work. It would have to be adjusted to load the correct assembly if run from an external tool though.

Assembly asm = Assembly.GetExecutingAssembly();
foreach (Type type in asm.GetTypes())
{
 if(type.GetInterface(typeof(IDisposable).FullName)  != null)
 {
  // Store the list somewhere
 }
}

Upvotes: 0

Related Questions