tags:

views:

366

answers:

3

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?

+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
+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
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
@LBushkin - ValueType is doable via : struct (although that excludes Nullable<T>)
Marc Gravell
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