I’m trying to create a class that works as a flexible enum.
I came with this idea, with 2 additional static methods that allow me to add new members to that list and get only members from that list.
public class LikeEnum
{
private static List<LikeEnum> list = new List<LikeEnum>()
{ new LikeEnum("One"), new LikeEnum("Two") };
private string value;
private LikeEnum(string value)
{
this.value = value;
}
}
Unfortunately the List list is only initialized as null so this doesn’t work…
Any ideas or suggestions?
No, it’s not “initialized as null”. It’s just never initialized… The static constructor (implicit in your case) is only executed the first time a static field of the class is accessed. Since you can’t create an instance (constructor is private) and there are no public static members, the class stays uninitialized…
Anyway, for what your trying to do, the
List<LikeEnum>is not very useful… a better option, if you want it to be like an enum, would be to create static readonly fields :EDIT : by the way, I assume you did not post the complete code of your class ? With the code you posted, there’s no way to get a
TypeInitializationException, since the type will never be initialized…