I need to specify that a Generic type should only accept enumerated types only in the closed type. Can anyone suggest a way to do this if contraints cannot work?
views:
366answers:
3
+2
A:
Closest constraint is struct:
class C<E> where E : /* enum */ struct
If you need to make sure it is an enum use typeof ( E ).IsEnum
baretta
2009-02-11 10:20:23
+4
A:
You can't do this directly in C# - the enum type is not usable as a constraint. One option (grungy) is to use a type-initializer (static constructor) to do the checking at runtime. It'll stop it using inappropriate types at runtime, but not at compile time.
class Foo<T> where T : struct {
static Foo() {
if (!typeof(T).IsEnum) {
throw new InvalidOperationException("Can only use enums");
}
}
public static void Bar() { }
}
enum MyEnum { A, B, C }
static void Main() {
Foo<MyEnum>.Bar(); // fine
Foo<int>.Bar(); // error
}
Marc Gravell
2009-02-11 10:30:44
This can be a frustrating limitation of .net at times - especially since Enum is not the only type that is excluded from being used in a constraint - so are: System.Delegate, System.Array, and System.ValueType.
LBushkin
2009-06-12 17:58:30
@LBushkin - ValueType is doable via : struct (although that excludes Nullable<T>)
Marc Gravell
2009-06-13 07:52:14
A:
Since you said you can't use constraints, the only other solution it came to my mind is to use dynamic cast and check at runtime the result. This is far worst from using constraints as solution. However, here you can find an article that might help.
Stefano Driussi
2009-02-11 10:31:26