user3751027
user3751027

Reputation: 27

Method Only Works Once? C#

I'm starting to think this is a stupid question, because I cannot find anything related but here goes.

So I've been learning C# and trying to figure out methods, so I created a simple method that increases a variable when used. So then I attached it to a button in Microsoft Visual Forms. However it only seems to increase the value once and then the computer stops executing the method.

Here's My Code

 public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();
     }

     int number = 0;

     public void button1_Click(object sender, EventArgs e)
     {
         NumberMethod(number);
     }

     public int NumberMethod(int number)
     {
         number++;
         label1.Text = number.ToString("Number:#");
         return number;
     }
 }

So again I want it to execute the method and increase the variable every time someone clicks the button.

Upvotes: 0

Views: 433

Answers (1)

Raging Bull
Raging Bull

Reputation: 18747

Try using this keyword:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    int number = 0;
    public void button1_Click(object sender, EventArgs e)
    {
        NumberMethod();
    }
    public int NumberMethod()
    {
        this.number++;
        label1.Text = this.number.ToString("Number:#");
        return this.number;
    }
}

Explanation:

When you invoke NumberMethod(number) it passes only the value which is initially zero. And that is incremented by 1 from the function. The important thing is the value of the variable number is not changed yet (it remains zero). The same happens again and again.

In my solution, we are not passing the value, but changing the value of number from the method itself.

Upvotes: 2

Related Questions