C
C#8mo 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
mtreit8mo ago
Isn't "this" just the attribute itself?
nut
nutOP8mo ago
cant you access the type via the attribute? idk attributes are kinda confusing for me since im more used to c/c++
mtreit
mtreit8mo ago
You use the word implementing but I assumed you meant "decorated with"
nut
nutOP8mo 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
mtreit8mo 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
nutOP8mo ago
thats aight i was just trying to simplify something that already works so its no biggie thanks
Pobiega
Pobiega8mo 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.
Want results from more Discord servers?
Add your server