Mathew
Mathew

Reputation: 93

Ref int question in C#

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

Upvotes: 8

Views: 18368

Answers (5)

ABCD
ABCD

Reputation: 907

ref

NumberUp(ref number );

Upvotes: -1

user195488
user195488

Reputation:

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.

Upvotes: 1

dowhilefor
dowhilefor

Reputation: 11051

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.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

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

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

Upvotes: 1

SLaks
SLaks

Reputation: 888303

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.

Upvotes: 25

Related Questions