Attribute restriction for generic type in .net?

in.net, if I have a generic class SomeClass<T>, can I use a keyword whereto require that T be a class with a specific attribute? sort of:

[SomeAttribute]
class MyClass
{
    ...
}

class AnotherClass<T> where T : Attribute(SomeAttribute)
{
    ...
}
+3
source share
2 answers

No, It is Immpossible.

The closest thing you can do is require the class to implement a specific interface.

+3
source

No, you cannot, but you can get around this by checking the attribute in the static constructor:

public class MyType<T> {
    static MyType() {
        // not compile checked, something like:
        if (!Attribute.IsDefined(typeof(T), typeof(MyAttribute))
            throw new ArgumentException();   // or a more sensible exception
    }
}
+2
source

Source: https://habr.com/ru/post/1751297/


All Articles