Search code examples
c#staticrecords

Any ideas why this static class is not initialising?


I'm currently working on a program for a uni project that involves building a 'tamagotchi' program, but I've run across an error quite early on related to the class construct I've used for storing the values related to each pet as part of a record. However, when I trace the program, the variables do not appear to initialize and it throws up a NullReferenceException once the program calls the variable for the first time. Any ideas on why?

static class GlobalVars     // Static class used to store pet values as 'global' variables.
{
    public static TTamagotchiPet Pet1 { get; set; }
    public static TTamagotchiPet Pet2 { get; set; }
    public static TTamagotchiPet Pet3 { get; set; }
    public static TTamagotchiPet Pet4 { get; set; }
}

public void frmTamagotchi_Load(object sender, EventArgs e)      // On Load event; initialises Pet 1.
{
    tmrUpdate.Enabled = true;
    GlobalVars.Pet1.Active = true;
    //GlobalVars.Pet1.Dead = false;
    //GlobalVars.Pet1.FunValue = 0;
    //GlobalVars.Pet1.FoodValue = 0;
    //GlobalVars.Pet1.HealthValue = 0;
    //GlobalVars.Pet1.ExertionValue = 0;
    //GlobalVars.Pet2.Active = false;
    //GlobalVars.Pet3.Active = false;
    //GlobalVars.Pet4.Active = false;
}

private void tmrUpdate_Tick(object sender, EventArgs e)     // Update timer. Each tick reduces pet attributes and checks to see if a pet has died, and controls pet states for the animation timer.
{
// First section updates pet attributes and checks to see if health reaches the 100 limit - at which point the pet dies.
    if (GlobalVars.Pet1.Active == true)  //code crashes here
    {
        if (GlobalVars.Pet1.Dead == false)
        {

The code also skips out the rest of the initialization (where I've commented out numerous lines in the frmTamagotchi_load method) even when the lines are uncommented; could this be related to the issue?


Solution

  • You never set the values for the pets themselves.

    You need to put the following in your Load method or your constructor:

    GlobalVars.Pet1 = new TTamagotchi();
    GlobalVars.Pet2 = new TTamagotchi();
    GlobalVars.Pet3 = new TTamagotchi();
    GlobalVars.Pet4 = new TTamagotchi();
    

    At the start of your program, these Pet1...Pet4 values are null, and remain so unless you explicitly instantiate them, as in the code above.

    If you put this code in a constructor, make sure it is a static one, as GlobalVars is a static class.