Smarc
Smarc

Reputation: 55

C# accessing class instance from method

Seems like I'm struggling with a pretty basic problem right now, but I just can't find a good solution..

I have this code-snippet here:

    public Form1()
    {
        InitializeComponent();

        BaseCharacterClass myChar = new BaseCharacterClass();
    }

    public void setLabels()
    {
        lbName.Text = myChar.CharacterName;
        lbHealthPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharHPmax);
        lbMagicPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharMPmax);
        lbClass.Text = myChar.CharacterClass;
    }

It says "myChar" does not exist in the current scope..

How do I fix that?

Upvotes: 0

Views: 1711

Answers (2)

Takarii
Takarii

Reputation: 1648

You didnt declare the variable as a class variable, only a local one. In c# the format is:

MyNamespace
{
    class MyClassName
    {
        //class wide variables go here
        int myVariable; //class wide variable

        public MyClassName() //this is the constructor
        {
            myVariable = 1; // assigns value to the class wide variable
        }

        private MyMethod()
        {
            int myTempVariable = 4; // method bound variable, only useable inside this method

            myVariable = 3 + myTempVariable; //myVariable is accessible to whole class, so can be manipulated
        }
    }
}

And so on. Your current constructor only declares a local variable within the constructor, not a class wide one

Upvotes: 0

NicoRiff
NicoRiff

Reputation: 4883

You just need to declare myChar outside of the constructor. You can define it on the class and then assign it on the constructor:

BaseCharacterClass myChar;

public Form1()
        {
            InitializeComponent();

            myChar = new BaseCharacterClass();
        }

        public void setLabels()
        {
            lbName.Text = myChar.CharacterName;
            lbHealthPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharHPmax);
            lbMagicPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharMPmax);
            lbClass.Text = myChar.CharacterClass;
        }

Upvotes: 3

Related Questions