Reputation: 5478
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
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
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
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