What I want to do here is a bit hard to describe. My current needs require that I have an enum type that can implement an interface. While not the prettiest solution, this is what I came up with;
public class EnumClass<T> where T : Enum
{
public T Value { get; }
public string Name { get; }
public EnumClass(T enumValue)
{
Value = enumValue;
Name = Enum.GetName(typeof(T), enumValue);
}
public static EnumClass<T> Parse(string name)
{
return new EnumClass<T>((T)Enum.Parse(typeof(T), name));
}
}
Here is an example implementation:
public class AnimalTypes : EnumClass<AnimalTypesEnum>, IMyEnumInterface
{
public AnimalTypes (AnimalTypesEnum value) : base(value) { }
}
public enum AnimalTypesEnum
{
[Description("Cat")]
CAT,
[Description("Dog")]
DOG,
[Description("Horse")]
HORSE,
[Description("Bear")]
BEAR
}
When I call Parse
statically on an inheritor, I have to manually cast the result back to the inheritor type from the base type, since Parse
returns a generic EnumClass<T>
object.
ex.
AnimalTypes dog = (AnimalTypes)AnimalTypes.Parse("DOG");
My question essentially is, is there any way to write Parse
such that it returns the type of the inheritor, and not the base class? I'd also like to be able to mark EnumClass<T>
abstract, but if I try doing so now, the compiler will not compile Parse
, stating that I cannot create an abstract instance of type EnumClass<T>
with which to return.