Home > OS >  Static list is initialized with different items but has only one type during runtime
Static list is initialized with different items but has only one type during runtime

Time:10-19

I was trying to emulate an enum in C# i can use with string values by using a class with static only members like here:

internal class TruckSizeType
{
  private static string? Value;

  private TruckSizeType(string value) { Value = value; }

  public static TruckSizeType SMALL { get { return new TruckSizeType("small"); }}
  public static TruckSizeType MEDIUM { get { return new TruckSizeType("medium"); }}
  public static TruckSizeType BIG { get { return new TruckSizeType("big"); }}
  public static TruckSizeType GIANT { get { return new TruckSizeType("giant"); }}
  public static List<TruckSizeType> ALL = new ()
  {
    SMALL,
    MEDIUM,
    BIG,
    GIANT
  };

  public override string ToString()
  {
    return Value ?? "";
  }
}

For some reason, the list member "ALL" shows up as filled with 4 members (which is correct) during runtime but all of those are of the type GIANT. I cannot figure out why all the members are of type GIANT in the ALL list when i initialized them with all of the 4 different types instead. Does anybody understand this? I am not a c# programmer but have quite a bit of experience in OOP languages. Perhaps it is a case of missing the obvious. Here is a screenshot from the debugger showing the value of the list after assignment: enter image description here

CodePudding user response:

I think you need to use static fields instead of properties so you don't create new instances each time you reference them, and you need to have an actual class with a private value to hold the string:

internal class TruckSizeType {
    private readonly string Value;
    private TruckSizeType(string value) => Value = value;

    public static readonly TruckSizeType SMALL = new TruckSizeType("small");
    public static readonly TruckSizeType MEDIUM = new TruckSizeType("medium");
    public static readonly TruckSizeType BIG = new TruckSizeType("big");
    public static readonly TruckSizeType GIANT = new TruckSizeType("giant");
    public static readonly ReadOnlyCollection<TruckSizeType> ALL = new List<TruckSizeType>() { SMALL, MEDIUM, BIG, GIANT }.AsReadOnly();

    public override string ToString() => Value ?? "";
}
  • Related