Lonzo
Lonzo

Reputation: 2818

How to limit a generic type 's type arguments to a specific type besides using constraints?

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?

Upvotes: 3

Views: 1321

Answers (3)

baretta
baretta

Reputation: 7585

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

Upvotes: 2

Stefano Driussi
Stefano Driussi

Reputation: 2261

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.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062492

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
}

Upvotes: 5

Related Questions