Attribute constraint on a generic type in .net?
-
29-09-2019 - |
Question
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)
{
...
}
Solution
No, that's not possible.
The closest you can do is to require that the class implement a particular interface.
OTHER TIPS
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
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow