Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing static fields in C# for use in enum pattern
    primarykey
    data
    text
    <p>My question is actually about a way to work around how C# initializes static fields. I need to do this, in my attempt to duplicate a Java style enum. The following is an example of the code that shows the problem:</p> <p>A base class for all my enums to inherit from</p> <pre><code>public class EnumBase { private int _val; private string _description; protected static Dictionary&lt;int, EnumBase&gt; ValueMap = new Dictionary&lt;int, EnumBase&gt;(); public EnumBase(int v, string desc) { _description = desc; _val = v; ValueMap.Add(_val, this); } public static EnumBase ValueOf(int i) { return ValueMap[i]; } public static IEnumerable&lt;EnumBase&gt; Values { get { return ValueMap.Values; } } public override string ToString() { return string.Format("MyEnum({0})", _val); } } </code></pre> <p>A sample of an enumerated set:</p> <pre><code>public sealed class Colors : EnumBase { public static readonly Colors Red = new Colors(0, "Red"); public static readonly Colors Green = new Colors(1, "Green"); public static readonly Colors Blue = new Colors(2, "Blue"); public static readonly Colors Yellow = new Colors(3, "Yellow"); public Colors(int v, string d) : base(v,d) {} } </code></pre> <p>This is where the problem is:</p> <pre><code>class Program { static void Main(string[] args) { Console.WriteLine("color value of 1 is " + Colors.ValueOf(2)); //fails here } } </code></pre> <p>The above code fails because EnumBase.ValueMap contains zero items, because none of the constructors for Color have been called yet.</p> <p>It seems like this shouldn't be that hard to do, it is possible in Java, I feel like I must be missing something here?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload