7

Simply put, I am using a while loop to repeat a method, and each time the method is run the int "i" will increase by 1. Although I am having trouble calling the "NumberUp" method. error output is below.

Main method:

while (true)
{
    NumberUp(0);
}

NumberUp Method:

public static void NumberUp(ref int i)
{
    i++;
    System.Console.WriteLine(i);
}

I keep getting the following error:

The best overloaded method match for 'ConsoleApplication2.Program.NumberUp(ref int)' has some invalid arguments

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
Mathew
  • 83
  • 1
  • 1
  • 3
  • 2
    Are you trying to increment the value of the literal `0`? It doesn't maker sense to pass a literal as a `ref`. – SLaks Aug 10 '11 at 13:55
  • Possible duplicate of [Why use the 'ref' keyword when passing an object?](http://stackoverflow.com/questions/186891/why-use-the-ref-keyword-when-passing-an-object) – Jim Fell May 27 '16 at 17:08
  • @JimFell This is a separate issue. – Rob May 28 '16 at 04:43

5 Answers5

21

To call a method that takes a ref parameter, you need to pass a variable, and use the ref keyword:

int x = 0;
NumberUp(ref x);
//x is now 1

This passes a reference to the x variable, allowing the NumberUp method to put a new value into the variable.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Ref is used to pass a variable as a reference. But you are not passing a variable, you are passing a value.

 int number = 0;
 while (true)
 {
      NumberUp(ref number );
 }

Should do the trick.

dowhilefor
  • 10,971
  • 3
  • 28
  • 45
1

A ref parameter needs to be passed by ref and needs a variable:

int i = 0;
while (true)
{
    NumberUp(ref i);
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

You have to pass 0 as a reference in a variable containing 0, for instance:

int i = 0;
NumberUp(ref i);

Read here at MSDN for more information on the ref keyword.

-1

ref

NumberUp(ref number );
CharithJ
  • 46,289
  • 20
  • 116
  • 131
ABCD
  • 897
  • 16
  • 38