RumbleJungle RumbleJungle - 4 months ago 10
C# Question

Passing variable from one class to another

I'm currently unable to pass a variable from one class to another. My first class is the default made from my form named (Calculator). The second called record.

public void toolStripLabel1_Click(object sender, EventArgs e)
{

Record rec = new Record();
System.Windows.Forms.MessageBox.Show(calculation);
rec.startRecording();
}


The above when I click the the correct variable is displayed in the pop-up box.

namespace CalculatorV2
{
class Record
{
public void startRecording()
{
Calculator calc = new Calculator();
System.Windows.Forms.MessageBox.Show(calc.calculation);
using (StreamWriter writer =
new StreamWriter("important.txt"))
{
writer.WriteLine("Line one");
writer.WriteLine(calc.calculation);
writer.WriteLine("Line Two");
}
}
}
}


But when I call the method startRecording() the variable value is not pulled. Is this because a new class object of calculator is created in which the variable calculation is blank ? Any help would be appreciated.

Answer

Pass the instance of class to the method as parameter

class Record
{

    public void startRecording(Calculator calculator)
    {
        System.Windows.Forms.MessageBox.Show(calculator.calculation);
        using (StreamWriter writer =
        new StreamWriter("important.txt"))
        {
            writer.WriteLine("Line one");
            writer.WriteLine(calculator.calculation);
            writer.WriteLine("Line Two");
        }
    }
}

public void toolStripLabel1_Click(object sender, EventArgs e)
{
    Record rec = new Record();
    System.Windows.Forms.MessageBox.Show(calculation);

    rec.startRecording(this);
}
Comments