0

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?

2
  • 3
    You'll have to declare the variable outside of your method. Commented Dec 28, 2016 at 11:53
  • Paste the code here. declare the variable on the top of Form1 method Commented Dec 28, 2016 at 11:56

2 Answers 2

3

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;
        }
Sign up to request clarification or add additional context in comments.

3 Comments

Ow okay, great!
Done. :) May I be able to contact you somewhere else, because I got another question which includes rather more code.
Post it to Stack Overflow. It is the best way we can help.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.