I have the following class:
public class DocketType : Enumeration<DocketType, int, string>
{
public static DocketType ChangeOver = new DocketType(1, "Changeover");
public static DocketType Withdrawal = new DocketType(2, "Withdrawal");
public static DocketType Installation = new DocketType(3, "Installation");
private DocketType(int docketTypeId, string description)
: base(docketTypeId, description)
{
}
}
With the following base class:
public abstract class Enumeration<TEnum, X, Y> : IComparable
where TEnum : Enumeration<TEnum, X, Y>
where X : IComparable
where Y : IComparable
{
protected Enumeration(X value, Y displayName)
{
AddToStaticCache(this);
}
public static TEnum Resolve(X value)
{
return Cache[value] as TEnum;
}
}
The problem I have is that Changeover, Withdrawal and Installation are not being created when the first time that the static class is used is via the Resolve method in the base class. I.e. if I call Resolve, then Cache will be empty.
However, if I do something like DocketType foo = DocketType.Changeover; in Application_Start, then all of the static fields get created and then Cache has all three values.
What’s the correct way to create these static fields so this scenario works?
I don’t think the fields in
DocketTypeshould be initialised when all you’re accessing isEnumeration<>. You are not referencing theDocketTypetype at all when you callEnumeration<>.Resolve(). Should the CLR really initialise all subclasses every time you access a static method or static field? It would slow down your code, and in most cases unnecessarily so.You could try writing
Docket.Resolve(), which C# allows you to do, but I don’t know whether this will compile into something different than before; the compiler might just turn it intoEnumeration<DocketType, int, string>.Resolve()and you’re back to sqaure one.To be honest, I am inclined to suggest that your code structure is flawed, and the problem you’re running into is a symptom of that. You shouldn’t have to rely on
Cachecontaining something. You shouldn’t have to rely on some static type initialisation to have occurred when you’re not using that type.Therefore, your options are:
DocketTypesomewhere in yourMain()method to ensure the initialisation happens, and live with the idea that your code structure may be flawed.Enumeration<>itself, which alleviates the flaw but doesn’t completely solve it.