Access variables of different methods in C#
C# beginners may encounter difficulties in accessing and modifying variables defined in different methods. This can prevent smooth execution of your code, especially when dealing with variables that require interconnected operations.
In your particular scenario, you define two separate methods readG_TextChanged
and readQ_TextChanged
to read the value of text boxes named readG
and readQ
. You correctly convert these values to decimal numbers and store them as _Gd
and _Qd
respectively, but these variables are only valid within the scope of their respective methods.
This method cannot access button1_Click
and _Gd
in your button click event handler _Qd
. To solve this problem, you need to understand the concept of scope. Variables declared in a local scope (such as a method body) are only accessible within its scope.
The solution to this problem is to move the declarations of _Gd
and _Qd
to the class level. By declaring them as private member variables, you make them accessible to all methods in the class (including button1_Click
).
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>
Now, the button1_Click
method can access and use _Gd
and _Qd
, allowing you to perform the necessary operations and display the results in the console as expected.
The above is the detailed content of How Can I Access Variables from Different Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!