C# enum in interface/base class?

kaem picture kaem · Jun 23, 2009 · Viewed 36.9k times · Source

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

Answer

Rachel picture Rachel · Oct 19, 2010

It's amazing how often I find people arguing about why something is required, rather than answering the question asked or keeping schtum - either of which would be more helpful than wasting time questioning why a given enquiry has been made in preference to a different enquiry the respondent actually knows the answer to. Answering questions that have not been asked is in no way helpful, OK guys?!

Getting back to the topic at hand, I've hit exactly the above scenario this morning, and can understand why it would be useful to be able to define an Enum in an interface or base class, then re-define that same-named Enum in a class that derives from either the base or interface. One use for such a design is in object-relational mapping and control binding. You might have a set of Enums that describe which Properties of your derived classes are bindable to which types of Control, such as:

    public enum WebControlTextBoxProperties { }

    public enum WebControlLabelProperties { }

...and so on.

Since you don't know exactly which Properties will exist for a given derived class until the pertinent inheritance takes effect, but since you may also wish to have consistent Methods that consume the above Enums in your base or interface, it's a perfectly-valid design to expect to be able to define that the Enum will exist in the base/interface, but define exactly what members it has in a specific context in any derived classes.

I really wish this were possible in C# as it is in VB, because it'd be a really useful feature.