Reputation: 169
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?
Upvotes: 0
Views: 566
Reputation: 292695
Unfortunately the List list is only initialized as null so this doesn't work...
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 :
public class LikeEnum
{
public static readonly LikeEnum One = new LikeEnum("One");
public static readonly LikeEnum Two = new LikeEnum("Two");
private string value;
private LikeEnum(string value)
{
this.value = value;
}
}
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...
Upvotes: 4
Reputation: 76590
Since you said enum
I assume that you also want to use them in switch
statements. Here is an example that allows you to do that:
public struct LikeEnum
{
public const string One = "One";
public const string Two = "Two";
private readonly string value;
private LikeEnum(string value)
{
this.value = value;
}
public static implicit operator LikeEnum(string value) {
return new LikeEnum(value);
}
public static implicit operator string(LikeEnum le) {
return le.value;
}
}
//In the code
LikeEnum le = new LikeEnum("One");
switch(le) {
case LikeEnum.One:
//do something
break;
}
Upvotes: 0
Reputation: 14788
heres a more common pattern for what you are trying to do, i remember it was popular in java before 1.5
public sealed class LikeEnum
{
public static readonly LikeEnum One = new LikeEnum("one");
public static readonly LikeEnum Two = new LikeEnum("Two");
private string value;
private LikeEnum(string v)
{
value = v;
}
}
because the class is sealed
and the constructor is private the only enums that can be created are those that you specify.
Upvotes: 1