C# enum in interface/base class?

c#, enums, parent, virtual

Solution

There is no such thing as an abstract enum (that can have different implementations in subclasses) - but generics may be an option:

class Base<T> where T : struct {
    private T value;
    public void Foo(T value) {
        this.value = value;
    }
}
class Parent1 : Base<Parent1.Enum1> {
    public enum Enum1 {A, B, C};
}
class Parent2 : Base<Parent2.Enum2> {
    public enum Enum2 { J, H, K };
}

The only problem is that this doesn't enforce that only enums are usable - you can do this at runtime, though - for example in a type initializer:

static Base() {
    if (!typeof(T).IsEnum) throw new InvalidOperationException(
         typeof(T).Name + " is not an enum");
}

Problem

i have problem with enum I need make a enum in base class or interface (but empty one) ``` class Base { public enum Test; // ??? } ``` and after make diffrent enums in some parent classes ``` class Parent1 { public enum Test {A, B, C}; } class Parent2 { public enum Test {J, H, K}; } ``` and now i have next class with method when i have to use enum ``` class Test<T> { public void Foo(Test enum) { int value = (int) enum; // ... } } ``` It's there any way to do something like that ? If not i have to use static ints in every class ... ``` class Parent1 { public static int A = 0; public static int B = 5; public static int C = 7; } class Parent2 { public static int J = 1; public static int H = 3; public static int K = 6; } class Test<T> { public void Foo(int enum) { int value = enum; // ... } } ``` I't looks bad in code ... in some classes i have to use ~20+ variables

Original source