Search code examples
c#.netgenericsreflectioncustom-attributes

Type constraints in Attributes


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?


Solution

  • Very simple to your final question:

    so finally question is: how can I check in compile time (like T constraints) that type is implementing some interface?

    You can not do that.

    But you can check it at runtime, with some reflection methods like: Type.IsAssignableFrom