César Amorim
César Amorim

Reputation: 357

Use a variable from another method in C#

I am new to C# programming and am very inexperienced.

I'm creating a form with a text box, and I want my program to read numbers in that box in a method, and execute an operation with those numbers in another method. Here's how it is by now:

public void readG_TextChanged(object sender, EventArgs e)
{
    string _G = readG.Text;
    decimal _Gd = Convert.ToDecimal(_G);
}

public void readQ_TextChanged(object sender, EventArgs e)
{
    string _Q = readQ.Text;
    decimal _Qd = Convert.ToDecimal(_Q);
}
private void button1_Click(object sender, EventArgs e)
{
    decimal _ULS = (1.35m * _Gd + 1.5m * _Qd);
    Console.WriteLine("{0}", _ULS);
}

readQ, readG are the boxes names. button1 is the button to proceed to the operation, and display it in a console.

So far I have the _Gd and _Qd out of context in the button1_click method. Besides that, I think it will run pretty fine.

Upvotes: 0

Views: 1523

Answers (2)

Baldrick
Baldrick

Reputation: 11840

This concerns variable scope. The variables _Qd and _Gd only have scope within their methods.

You could make them class members, that is declare them outside your methods, in the main body of the class, as follows:

 private decimal _Gd;
 private decimal _Qd;

.

Then you can set them like this:

 _Gd = Convert.ToDecimal(_G);
 _Qd = Convert.ToDecimal(_Q);

These variables will be visible from within any method in your class.

Upvotes: 1

Sadek Noureddine
Sadek Noureddine

Reputation: 577

You should read up on scoping... http://msdn.microsoft.com/en-us/library/ms973875.aspx

One way is for your _Qd and _Gd to be at the class level, not defined within the methods themselves, so that you have access to them in the click method.

private decimal _Gd;
private decimal _Qd;
public void readG_TextChanged(object sender, EventArgs e)
{
    string _G = readG.Text;
    _Gd = Convert.ToDecimal(_G);
}

public void readQ_TextChanged(object sender, EventArgs e)
{
    string _Q = readQ.Text;
    _Qd = Convert.ToDecimal(_Q);
}
private void button1_Click(object sender, EventArgs e)
{
    decimal _ULS = (1.35m * _Gd + 1.5m * _Qd);
    Console.WriteLine("{0}",_ULS);
}

Upvotes: 3

Related Questions