C
C#3mo ago
nut

Getting all types that implement a custom attribute

hey, is using Assembly.GetTypes() and iterating them really the best way to get all types that implement a custom attribute? i was thinking i could just have a static enumerable in the attribute class like so:
class ExampleAttribute : System.Attribute
{
private static readonly List<ExampleAttribute> implementingTypes = new();

public ExampleAttribute()
{
implementingTypes.Add(this);
}

public static List<ExampleAttribute> ImplementingTypes => implementingTypes;
}
class ExampleAttribute : System.Attribute
{
private static readonly List<ExampleAttribute> implementingTypes = new();

public ExampleAttribute()
{
implementingTypes.Add(this);
}

public static List<ExampleAttribute> ImplementingTypes => implementingTypes;
}
7 Replies
mtreit
mtreit3mo ago
Isn't "this" just the attribute itself?
nut
nut3mo ago
cant you access the type via the attribute? idk attributes are kinda confusing for me since im more used to c/c++
mtreit
mtreit3mo ago
You use the word implementing but I assumed you meant "decorated with"
nut
nut3mo ago
yeah basically ive got a state machine and atm states need to be registered manually but i was thinking i could use an attribute to do somethingl ike
[RegisterWith(typeof(MyStateMachine)]
public class MyState : State<MyStateMachine> {}
[RegisterWith(typeof(MyStateMachine)]
public class MyState : State<MyStateMachine> {}
mtreit
mtreit3mo ago
No you can't access the type the attribute is decorating from within the attribute as far as I know It's possible I'm wrong but "this" definitely doesn't mean that
nut
nut3mo ago
thats aight i was just trying to simplify something that already works so its no biggie thanks
Pobiega
Pobiega3mo ago
you need to use reflection and find all public types that have this attribute. There is a method on Type for the "has my attribute" part.