C# ref and out
A Method Gets a Copy
When you pass a variable to a method, the method gets a copy of the value.
If the method changes the parameter, it only changes the copy. The original variable keeps its value:
Example
static void AddPoints(int points)
{
points = points + 10;
Console.WriteLine("Inside the method: " + points);
}
static void Main(string[] args)
{
int score = 5;
AddPoints(score);
Console.WriteLine("After the method: " + score);
}
Inside the method, points is 15. But score is still 5, because the method only changed its own copy.
This is usually what you want: a method cannot change your variables by mistake. But sometimes you want a method to change the original variable. For that, C# has the ref keyword.
The ref Keyword
The ref keyword passes the variable itself to the method, not a copy. When the method changes the parameter, the original variable changes too.
Write ref in two places: before the parameter type, and before the argument when you call the method:
Example
static void AddPoints(ref int points)
{
points = points + 10;
Console.WriteLine("Inside the method: " + points);
}
static void Main(string[] args)
{
int score = 5;
AddPoints(ref score);
Console.WriteLine("After the method: " + score);
}
Now score is 15 after the method call.
A good use of ref is a method that swaps (exchanges) the values of two variables:
Example
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int x = 10;
int y = 20;
Console.WriteLine("Before: x = " + x + ", y = " + y);
Swap(ref x, ref y);
Console.WriteLine("After: x = " + x + ", y = " + y);
}
The temp variable holds the value of a for a moment, so it is not lost when a gets the value of b.
Without ref, the method would only swap its own copies, and x and y would not change.
The out Keyword
A method can only return one value. The out keyword lets a method give back an extra value, through a parameter.
The following method shares coins between players. It returns how many coins each player gets, and it gives back the coins that are left with out:
Example
static int ShareCoins(int coins, int players, out int left)
{
left = coins % players;
return coins / players;
}
static void Main(string[] args)
{
int left;
int each = ShareCoins(17, 5, out left);
Console.WriteLine("Each player gets " + each + " coins");
Console.WriteLine("Coins left: " + left);
}
17 coins shared by 5 players is 3 coins each, and 2 coins are left. The % operator gives the remainder of a division.
Like ref, you write out both in the method and in the call.
The variable left does not need a value before the call. The method must give the out parameter a value before it ends.
int.TryParse()
You will often see out in a method that is built into C#: int.TryParse().
In the User Input chapter, you used Convert.ToInt32() to convert text to a number. If the text is not a number, like "abc", the program stops with an error.
int.TryParse() tries to convert a string to an int, without stopping the program:
- It returns
trueif it worked, andfalseif not. - It puts the converted number in the
outvariable.
Example
bool success = int.TryParse("123", out int number);
Console.WriteLine(success); // True
Console.WriteLine(number); // 123
out int number creates the variable number right inside the method call, so you do not need to declare it on a line before.
Use int.TryParse() in an if statement to check the text before you use the number:
Example
string text = "abc";
if (int.TryParse(text, out int number))
{
Console.WriteLine("The number is " + number);
}
else
{
Console.WriteLine(text + " is not a number");
}
ref or out?
| ref | out | |
|---|---|---|
| Must the variable have a value before the call? | Yes | No |
| Must the method give it a value? | No | Yes |
| Use it when | the method should change an existing variable | the method should give back an extra value |