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 Wizard Says No More War
  • 64,101
  • 26
  • 136
  • 201
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

20

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
  • 837,282
  • 173
  • 1,862
  • 1,933
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,822
  • 3
  • 26
  • 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
  • 166,158
  • 40
  • 312
  • 426
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
  • 44,463
  • 20
  • 111
  • 128
ABCD
  • 867
  • 16
  • 38