Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 710
Mathew Avatar asked Aug 10 '11 13:08

Mathew


2 Answers

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.

like image 50
SLaks Avatar answered Oct 07 '22 00:10

SLaks


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.

like image 30
dowhilefor Avatar answered Oct 07 '22 00:10

dowhilefor