How do I reference a variable from one class to another?

Viewed 147

I'm new to C# and I can't figure out how to reference the value of a variable from one class to another.

It's set to when the button is pressed, it'll take the text in the text box and sets that as "alphaask". Then it instances "alphaanswer" which would tell the label to change its text.

"alphaanswer" will take the value "alphaQuest" and see if its equal to "bob" which then would change the label.

ALL I want to know how to set the value of "alphaQuest" from the value of "alphaask" so the string can check it with "alphaanswer"

public partial class QuestionTab : Form
{
    public string alphaask = "null";

    public void button1_Click(object sender, EventArgs e)
    {
        // alphabutton
        // Checks if something is in textbox then says bool is true
        bool asked = false;
        if(textBoxAlpha.Text != "")
        {
            alphaask = textBoxAlpha.Text;
            asked = true;
        }

        if(asked==true)
        {

            // If bool is true than instance auxy
            var instance = new Alpha();
            instance.alphaanswer();

        }
    }
}

public class Alpha
{
    string alphaQuest = // <-- I want to make alphaQuest equal to alphaask

    alphaanswer();

    public void alphaanswer()
    {
        if (alphaanswer == bob)
         {
          //change text in label1
         }
        }
    }
2 Answers

Do these changes

public partial class QuestionTab : Form
{
    public string alphaask = "null";

    public void button1_Click(object sender, EventArgs e)
    {
        bool asked = false;
        if(textBoxAlpha.Text != "")
        {
            alphaask = textBoxAlpha.Text;
            asked = true;
        }

        if(asked==true)
        {

            // If bool is true than instance auxy
            var instance = new Alpha();
            instance.alphaAnswer(alphaask); 
            //Here you are sending the current value of alphaAsk to the alphaanswer method.
        }
    }
}


public class Alpha
{
    public void alphaAnswer(string alphaAnswer) //This string receives the value you sent
    {
        if (alphaAnswer == "bob")
         {
          //change text in label1
         }
    }
}

make a contractor in class Alpha with String parameter

public Alpha(String value)
{
}

then when you call it

var instance = new Alpha(alphaask);
instance.show();
Related