In order to use Enum's in combination with strings, I implemented a StringEnum class based on https://stackoverflow.com/a/424414/1293385.
However I run into problems when I try to implement the suggested user-defined conversion operations.
The StringEnum class is defined as follows:
public abstract class StringEnum
{
private readonly String name;
private readonly int value;
protected static Dictionary<string, StringEnum> instances
= new Dictionary<string, StringEnum>();
protected StringEnum(int value, string name)
{
this.value = value;
this.name = name;
instances.Add(name.ToLower(), this);
}
public static explicit operator StringEnum(string name)
{
StringEnum se;
if (instances.TryGetValue(name.ToLower(), out se))
{
return se;
}
throw new InvalidCastException();
}
public override string ToString()
{
return name;
}
}
I use this class as a base like this:
public class DerivedStringEnum : StringEnum
{
public static readonly DerivedStringEnum EnumValue1
= new DerivedStringEnum (0, "EnumValue1");
public static readonly DerivedStringEnum EnumValue2
= new DerivedStringEnum (1, "EnumValue2");
private DerivedStringEnum (int value, string name) : base(value, name) { }
}
However when I try to cast it using
string s = "EnumValue1"
DerivedStringEnum e = (DerivedStringEnum) s;
An InvalidCastException is returned. Inspection of the code shows that the instances attribute of the StringEnum class is never filled.
Is there an easy way to fix this?
I prefer not to use C# attribute "magic" such as [StringValue("EnumValue1")].
Thanks!