Search code examples
c#.netvariables.net-coremethods

C# Calling methods in methods


I have a code that will calculate something when button is clicked. The calculation formulas will vary, based on which radio button that is checked. Some of the calculation input will stay the same, independant of what radio buttons that are checked. So what I want to do, is to create a method that will be called upon in two different methods (case 1 and case 2), but I can't access the variables defined in calculationInput when called upon in the method for case 1 and 2, I get "the name does not exist in the current context". Can anyone help?

See below for a code example:

// Calculation input that will stay the same for each case
private void calculationInput(oject sender, EventArgs e)
{
    double a = 100;
    double b = 200;
    double c = 300;
}

//Case 1
private void calculationCaseOne(object sender, EventArgs e)
{
    calculationInput(new object(), new EventArgs());
    double case1 = a+b;
    label.Text=case1.ToString();
}

//Case 2
private void calculationCaseTwo(object sender, EventArgs e)
{
    calculationInput(new object(), new EventArgs());
    double case2 = a+c;
    label.Text=case2.ToString();
}

private void button1_Click(object sender, EventArgs e)
{
    if (radioButton1.Checked == true)
    {
        calculationCaseOne(new object(), new EventArgs());
    }
    if (radioButton2.Checked == true)
    {
        calculationCaseTwo(new object(), new EventArgs());
    }
}

Solution

  • In the current implementation, the variables a, b, and c are local variables defined within the calculationInput method, so they are not accessible from outside of that method.

    You will need to define them as fields of the class rather than local variables within a method.

    public partial class Form1 : Form
    {
        // Fields that will hold the calculation input
        private double a;
        private double b;
        private double c;
    
        // Method that initializes the calculation input
        private void calculationInput()
        {
            a = 100;
            b = 200;
            c = 300;
        }
    
        // Case 1
        private void calculationCaseOne()
        {
            calculationInput();
            double case1 = a + b;
            label.Text = case1.ToString();
        }
    
        // Case 2
        private void calculationCaseTwo()
        {
            calculationInput();
            double case2 = a + c;
            label.Text = case2.ToString();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                calculationCaseOne();
            }
            if (radioButton2.Checked == true)
            {
                calculationCaseTwo();
            }
        }
    }