Search code examples
c#variablesinitializing

Class variables not initializing


I have a really bizarre problem that seems like some sort of compiler error, but I also feel like that's really unlikely.

I have two nested classes that both have class variables. One of them (SpriteList) works perfectly fine and initializes all of the variables perfectly. When I breakpoint it, the program does break when initializing that class.

The other nested class (ItemList) is acting a little weird. The class variable in it isn't initializing and when I breakpoint the code, the program never breaks.

This is my code:

class Registry
{
    public static Dictionary<string, StaticSprite> spriteRegistry = new Dictionary<string, StaticSprite>();
    public static Dictionary<string, Item> itemRegistry = new Dictionary<string, Item>();

    public static void registerSprite(string name, StaticSprite sprite)
    {
        spriteRegistry.Add(name, sprite);
        Console.WriteLine("Registered Sprite: " + name + "!");
    }

    public static void registerItem(string name, Item item)
    {
        itemRegistry.Add(name, item);
        Console.WriteLine("Registered Item: " + name + "!");
    }

    public class ItemList
    {
        public static Item test = new ItemTest();
    }

    public class SpriteList
    {
        public static StaticSprite rock = new SpriteRock();
        public static StaticSprite pedestal = new SpritePedestal();
        public static StaticSprite item = new SpriteItem();
    }
}

I really have no idea what is wrong here. Neither class is constructed anywhere, not that is should matter. When I move the variables in ItemList into SpriteList, it runs fine.

I really have no clue as to what's wrong here.


Solution

  • Without a good, minimal, complete code example that reliably reproduces the problem, it's impossible to know for sure what the problem is.

    But note that the runtime is not required to initialize a class until that class is actually used at runtime. That is, at the point in which some code executes that actually needs that class.

    A breakpoint in static initialization (e.g. a static constructor, method called by a static initializer, etc.) may never be hit, and the code never executed, if the class from which that code is called is itself never actually used in the program.

    It seems likely to me that's what the issue is here. If there is no code that ever actually uses the ItemList class, then there's no need for a static field in the class to be initialized, and so…it isn't ever initialized.