C # function error to increment variable

6

I'm new and I have some "basic" questions.

I am doing a point counter, because many players want to create the function decrement / increment.

Increment function

    public void incremento(int pt, int mago)
    {
        pt++;
        switch (mago) { 
            case 1:
                labelM1.Text = String.Format("{0} Pontos", pt);
                break;

        }
     }

Button + (increase)

 private void M1mais_Click(object sender, EventArgs e)
    {
        incremento(pt1, mago1);
    }

But on the label where the current total of points should appear only increases the first time.

What's wrong? Is this the best way?

    
asked by anonymous 11.03.2014 / 05:25

3 answers

9

Its increment function performs the increment but the value of the variable is lost. The ideal function would be to increase the value of the variable pt .

This can be done like this:

public void incremento(ref int pt, int mago)
{
    pt++;
    switch (mago) { 
        case 1:
            labelM1.Text = String.Format("{0} Pontos", pt);
            break;
        default:
            break;
    }
}
    
11.03.2014 / 05:33
3

The main problem is you are not making use of Object Orientation. But let's break it down.

Solution 1

You are passing a Type variable by value as a parameter. You are using an int . An int is a value type . When you pass a value type as an argument to a function, it receives only a COPY of its variable, not its variable. That is: it wraps the value in the function but you do not see the change outside it.

To resolve this, you should use the ref modifier, as quoted by @Gigano there. This will cause the parameter to be passed by reference. Your method will act on your variable (same memory address) and no longer on a copy of it. But it has to be both the definition of the method and the call of the method.

You do not often perceive this error with reference type variables - briefly everything else that is not Value type (all types of Int and Float , decimal and structs ) - because in practice it's as if the object being passed as a reference.

Solution 2

Refactor. I would say that although the code compile and work, the general logic is essentially misleading, from the point of view of object orientation.

In my opinion you should be passing an object of type Mage as argument and not two int. It may sound like bullshit right now, but you better start right.

    
11.03.2014 / 18:37
0
The problem is that since the pt parameter becomes a copy of pt1 when you call the incremento method, only the value of pt (within the method) is modified, while of pt1 (outside) remains the same.

An alternative would be to separate the values of your label in two: one after (corresponding to the text "Points") and one before the blank space ('') corresponding to the number, using the

11.03.2014 / 13:17