Home > Backend Development > C++ > How Can I Access Variables from One Method in Another in C#?

How Can I Access Variables from One Method in Another in C#?

Patricia Arquette
Release: 2025-01-17 09:57:14
Original
540 people have browsed it

How Can I Access Variables from One Method in Another in C#?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template