I want to write my enum with custom attributes, for example:
public enum SomeEnum: long
{
[SomeAttribute<MyClass1>]
Sms = 1,
[SomeAttribute<MyClass2>]
Email = 2
}
but attributes doesn't support generics. Well, the most similar solution is:
public enum SomeEnum: long
{
[SomeAttribute(typeof(MyClass1))]
Sms = 1,
[SomeAttribute(typeof(MyClass2))]
Email = 2
}
And here is problem: I want Class1
to be inherited from ICustomInterface
, so with generics I can write constraint:
[AttributeUsage(AttributeTargets.All)]
class SomeAttribute<T> : Attribute where T: ICustomInterface
{
}
but attributes doesn't support generics.
so finally question is: how can I check in compile time (like T
constraints) that type is implementing some interface?
Type.GetInterface
- but are you sure that you need this inside the attribute? I would guess it's more handy where you do something with classes having this attribute... – CowerAttributeUsage
. In runtime I can check by usingIsAssignableFrom
, but it's runtime validation. – PlebeianIValidator<T>
interface (and assorted implementations) instead. An attribute cannot be used in the way that you want to achieve. – Deafening