views:

20

answers:

2

in .net, if I have a generic class SomeClass<T>, is it possible to use the where keyword to require that T is a class with a certain attribute? something like:

[SomeAttribute]
class MyClass
{
    ...
}

class AnotherClass<T> where T : Attribute(SomeAttribute)
{
    ...
}
+2  A: 

No, that's not possible.

The closest you can do is to require that the class implement a particular interface.

John Saunders
A: 

No you can't, but you can get round this by checking for 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
    }
}
thecoop