We are currently implementing some kind of "extensible enum class" based on strings. Only a part of this C# code is displayed below, to make the problem easier to understand.
If I run the code below, it writes "BaseValue1" and "BaseValue2" to the console.
If I uncomment the RunClassConstructor line and run the code, it additionally writes "DerivedValue1" and "DerivedValue2" to the console.
This is what I want to achieve, but I want to achieve it without the RunClassConstructor line.
I thought that DerivedEnum.AllKeys would trigger the creation of "DerivedValue1" and "DerivedValue2", but obviously this is not the case.
Is there a possibility to achieve what I want, without forcing the user of these "enum classes" to write some magic code, or to do some kind of dummy initialization?
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
public class Program
{
static void Main()
{
//System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(DerivedEnum).TypeHandle);
foreach (var value in DerivedEnum.AllKeys)
{
Console.WriteLine(value);
}
}
}
public class BaseEnum
{
private static readonly IDictionary<string, BaseEnum> _dictionary = new Dictionary<string, BaseEnum>();
public static ICollection<string> AllKeys
{
get
{
return _dictionary.Keys;
}
}
public static readonly BaseEnum BaseValue1 = new BaseEnum("BaseValue1");
public static readonly BaseEnum BaseValue2 = new BaseEnum("BaseValue2");
protected BaseEnum(string value)
{
_dictionary[value] = this;
}
}
public class DerivedEnum : BaseEnum
{
public static readonly DerivedEnum DerivedValue1 = new DerivedEnum("DerivedValue1");
public static readonly DerivedEnum DerivedValue2 = new DerivedEnum("DerivedValue2");
protected DerivedEnum(string value)
: base(value)
{
}
}
}