I have a base class for enumerations that looks similar to the example below. My actual implementation covers far more such as explicit and implicit castings, reflection, flags and exception handling, but basically, it's just this:
public abstract class Enumeration<T> {
// enum value
protected readonly T _value;
// collection of all values
private static readonly HashSet<Enumeration<T>> _values
= new HashSet<Enumeration<T>>();
public T Value {
get { return _value; }
}
// returns all values
public static IEnumerable<Enumeration<T>> GetValues() {
return _values.AsEnumerable();
}
}
Now, whenever I would like to have an enumeration of a certain type (may it be string, integer etc. I'm not so caged like with the usual C# enum), I can declare it this way:
public sealed class MyEnum : Enumeration<string> {
public static readonly MyEnum EnumVal1 = new MyEnum("Val1!");
public static readonly MyEnum EnumVal2 = new MyEnum("Val2!");
public static readonly MyEnum EnumVal3 = new MyEnum("Val3!");
}
And make it either expandable or not by using a private or public constructor:
public MyEnum(string enumVal) : base(value: enumVal) {}
which passes the values to the base ctor:
protected Enumeration(T value) {
_value = value;
_values.Add(this);
}
This works fine for types like string, int, double etc. But what if I would like to enumerate complex objects?
public sealed class ComplexObj: Enumeration<ComplexObj> {
public static readonly ComplexObj Val1 = new ComplexObj("val1", 455, null);
}
Here do the problems start, as I'm not able to pass the instanced objects to the base constructor:
public ComplexObj(string name, int someval, string another)
: base(this) {} // doesn't work
And passing a new object to the constructor would lead to.. you know :)
: base(new ComplexObj(name, someval, another)) {} // lol
How could I solve this problem? Is there a way to pass the object itself to the base constructor?