Get classes in assembly?
Messages   Related Types
This message was discovered on ASPFriends.com 'ngfx-reflection' list.
Responses highlighted in red are from those people who are likely to be able to contribute good, authoratitive information to this discussion. They include Microsoft employees, MVP's and others who IMHO contribute well to these kinds of discussions.

Andy Smith (VIP)
Is there any way to get all the classes in an assembly that directly or =
indirectly derive from a given class?
or that implement a given interface?

Reply to this message...
 
    
Mitch Denny (VIP)
Andy,

No problems! What you need to do is get an instance of
the Assembly class which represents the assembly that
you want to search. In the example that I am about to
run through our assembly is going to be called "Foo.dll".

You can load the assembly like this:

    Assembly fooAssembly = Assembly.LoadFrom("Foo.dll");

Once you have this object, you can call its GetTypes()
method. This returns an array of Type objects, here is
an example:

    Type[] fooTypes = fooAssembly.GetTypes();

Now, the following code is fairly straight forward, it
enumerates over the array created above, looks at the
BaseType of each of these classes and compares it to
a the base type to see if it is the same:

    Type searchType = Type.GetType("FooBaseType");

    foreach (Type individualType in fooTypes) {

        if (individualType.BaseType == searchType) {

            Console.WriteLine(
                "{0}.{1}",
                individualType.Namespace,
                individualType.Name
                );

        }

    }

Searching for interfaces is a little bit more involved
because you need to call the GetInterfaces() which returns
another array of Types which you need to search of again.

As a quick and dirty, you could embed another foreach
loop inside the first one, thusly:

    foreach (Type individualInterface in
individualType.GetInterfaces()) {

        if (individualInterface.BaseType == searchType) {

            Console.WriteLine(
                "{0}.{1}",
                individualInterface.Namespace,
                individualInterface.Name
                );

        }

    }

Anyway, there you have it. I haven't tested the
above code, but I am fairly confident that I haven't
made any typos or omissions. If you have any problems
with it, let me know and I will correct it accordingly.

----------------------------------------
- Mitch Denny
- http://www.warbyte.com
- Click here to reveal e-mail address
- +61 (414) 610-141
-

[Original message clipped]

Reply to this message...
 
 
System.Console
System.Reflection.Assembly
System.Type




Ad
MBR BootFX
Best-of-breed application framework for .NET projects, developed by Matthew Baxter-Reynolds and MBR IT
 
 Copyright © Matthew Baxter-Reynolds 2001-2008. '.NET 247 Software Development Services' is a trading style of MBR IT Solutions Ltd.
Contact Us - Terms of Use - Privacy Policy - www.dotnet247.com