Cross-method access to C# variables
When dealing with different objects and methods in a C# program, you may need to access variables defined in another method in one method. This article provides a solution to this common problem.
In the example, you are using a C# form that contains two text boxes named readG
and readQ
. Your goal is to read the values from these text boxes and perform operations on them in a separate method named button1_Click
. However, the current code attempts to use variables readG_TextChanged
and readQ_TextChanged
defined in the _Gd
and _Qd
methods, which are not accessible in button1_Click
.
To resolve this issue, the _Gd
and _Qd
variables must be moved outside the individual methods and declared as private class-level variables. By doing this, they are accessible throughout the class and can be used in button1_Click
and text change event handler methods.
The following is the modified code:
<code class="language-csharp">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); }</code>
This modified code places _Gd
and _Qd
at the class level, ensuring they are accessible within the button1_Click
method. The text change event handler updates these variables and uses their values when the button is clicked. This way you should be able to smoothly perform operations on the numbers entered in the text box.
The above is the detailed content of How Can I Access Variables from One Method in Another in C#?. For more information, please follow other related articles on the PHP Chinese website!