SharpAffair
SharpAffair

Reputation: 5478

.NET: Get all classes derived from specific class

I have a custom control and a number of controls derived from it. I need to get all classes in the current assembly that are derived from the main class and check their attributes. How to accomplish this?

Upvotes: 4

Views: 2410

Answers (3)

brewmanz
brewmanz

Reputation: 1221

To find derivatives of a class, which were all defined in another Assembly (GetExecutingAssembly didn't work), I used:

var asm = Assembly.GetAssembly(typeof(MyClass));
var listOfClasses = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(MyClass)));

(split over 2 lines to save scrolling)

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

You can use reflection:

Type baseType = ...
var descendantTypes =
    from type in baseType.Assembly.GetTypes()
    where !type.IsAbstract
       && type.IsSubclassOf(baseType)
       && type.IsDefined(typeof(TheCustomAttributeYouRequire), true)
    select type;

You can go from there.

Upvotes: 1

Ben M
Ben M

Reputation: 22492

var type = typeof(MainClass);

var listOfDerivedClasses = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(x => x.IsSubclassOf(type))
    .ToList();

foreach (var derived in listOfDerivedClasses)
{
   var attributes = derived.GetCustomAttributes(typeof(TheAttribute), true);

   // etc.
}

Upvotes: 11

Related Questions