What is the best way to "override" enums?
c#, enums, inheritance
Solution
The other answers are true, if you don't own or can't modify the original base class or enumeration. If you can, then you could use the typesafe enum pattern. It allows you to define your own enum types, not derived from enum, that do whatever you want them to do (including support inheritance).
public class MyEnum
{
public static readonly MyEnum A = new MyEnum("A");
public static readonly MyEnum B = new MyEnum("B");
public static readonly MyEnum C = new MyEnum("C");
public override string ToString()
{
return Value;
}
protected MyEnum(string value)
{
this.Value = value;
}
public string Value { get; private set; }
}
public sealed class MyDerivedEnum : MyEnum
{
public static readonly MyDerivedEnum D = new MyDerivedEnum("D");
private MyDerivedEnum(string value)
: base(value)
{
}
}
class Program
{
static void Main(string[] args)
{
MyEnum blah = MyEnum.A;
System.Console.WriteLine(blah);
blah = MyDerivedEnum.D;
System.Console.WriteLine(blah);
}
}
A D Press any key to continue . . .
Problem
Possible Duplicate: Enum “Inheritance” I have a number of classes which extend an abstract class. The abstract parent class defines an enum with a set of values. Some of the subclasses inherit the parent class's enum values, but some of the subclasses need the enum values to be different. Is there any way to somehow override the enum for these particular subclasses, and if not, what is a good way to achieve what I'm describing? ``` class ParentClass { private MyEnum m_EnumVal; public virtual MyEnum EnumVal { get { return m_EnumVal; } set { m_EnumVal = value; } } public enum MyEnum { a, b, c }; } class ChildClass : ParentClass { private MyEnum m_EnumVal; public virtual MyEnum EnumVal { get { return m_EnumVal; } set { m_EnumVal = value; } } public enum MyEnum { d, e, f }; } ```