Passing Values to a Method: by Value and by Reference
Learn what a method can and can't change in the code that calls it, passing by value, with ref and out, and passing an array.
Apprentice · C# · Updated
After this lesson you can
- Predict whether a method's change reaches the caller's variable when it's passed by value, with ref or out, or as an array
- Write a method with a ref or out parameter and call it with the matching keyword
Key takeaways
- By default C# passes a copy of each argument's value. A method that changes its parameter changes only its copy, and the caller's variable stays the same.
- With ref on the parameter and on the argument, the method works on the caller's own variable, so its changes stay after the call.
- An out parameter is a value the method hands back. The method must set it before it ends, and the call writes out, as in int.TryParse(typed, out int quantity).
- An array is a reference type. A method that changes an array's items changes the caller's array, but giving the parameter a new array doesn't change the caller's variable.
Your scoreboard program calls AddTouchdown(georgia), the method adds 6 points, and then Georgia's score on the board hasn't moved. Nothing crashed and nothing warned you: the method changed something, but not the variable you were looking at. Knowing what a method can and can't change in the code that calls it is how you avoid this bug, and how you write a method that hands back more than one answer.
By value: the method gets a copy
Here's the bug. The method adds a touchdown to its parameter and prints it; then the program prints Georgia's score again:
int georgia = 12;
AddTouchdown(georgia);
Console.WriteLine("After the call: " + georgia);
void AddTouchdown(int score)
{
score = score + 6;
Console.WriteLine("Inside the method: " + score);
}
Inside the method: 18
After the call: 12
Think of handing a friend a photocopy of your score sheet. They can write all over the copy; your sheet doesn't change. That's what a call does by default: C# copies the argument's value into the parameter. score starts as a copy of georgia's 12, the method changes the copy to 18, and georgia stays 12. This is called passing by value, and it's how every call you've written so far has worked.
Most of the time, it's what you want: a method can't change your variables behind your back. When a method should change the caller's value, the usual fix is to return the new value and store it: georgia = AddTouchdown(georgia); with a method that returns score + 6.
ref: the method works on the caller's variable
Sometimes a method really should change the caller's own variable. Instead of a photocopy, you hand over the score sheet itself. In C#, that's ref, short for reference:
int georgia = 12;
AddTouchdown(ref georgia);
Console.WriteLine("After the call: " + georgia);
void AddTouchdown(ref int score)
{
score = score + 6;
Console.WriteLine("Inside the method: " + score);
}
Inside the method: 18
After the call: 18
Now score isn't a copy: it's another name for georgia itself, so the change stays after the call. This is passing by reference. ref goes in two places, in the method's parameter (ref int score) and in the call (ref georgia), so anyone reading the call can see that the method may change the variable. Leave it out of the call and the program doesn't build:
int georgia = 12;
AddTouchdown(georgia);
void AddTouchdown(ref int score)
{
score = score + 6;
}
error CS1620: Argument 1 must be passed with the 'ref' keyword
A ref argument must be a variable that already has a value, because the method may read it before it changes it.
out: a method that hands back more than one value
A method returns one value. When it needs to give back two, it can use out parameters: values the method sends out to the caller. You've already called a method with one: int.TryParse(typed, out int quantity) returns true or false, and hands back the number through out.
Sharing a pizza is a question with two answers: how many slices each person gets, and how many are left over.
ShareSlices(17, 5, out int each, out int left);
Console.WriteLine("Each person gets " + each + " slices.");
Console.WriteLine(left + " slices are left over.");
void ShareSlices(int slices, int people, out int perPerson, out int leftOver)
{
perPerson = slices / people;
leftOver = slices % people;
}
Each person gets 3 slices.
2 slices are left over.
outgoes on the parameter and in the call, likeref.- The call can declare the variable right there,
out int each, asTryParsecalls do. - The method must give every
outparameter a value before it ends. If it doesn't, the program doesn't build: The out parameter 'perPerson' must be assigned to before control leaves the current method.
The difference between the two: ref is a variable going in and out (it has a value, and the method may change it); out only comes out (the method sets it, whatever it held before).
Passing an array: the method can change its items
An array holds several values in one variable, numbered from 0: in int[] quarterScores = { 12, 14, 6, 7 };, quarterScores[3] is the fourth quarter's 7. The Arrays in C# topic teaches arrays in full; here, watch what happens when one is passed to a method:
int[] quarterScores = { 12, 14, 6, 7 };
AddFieldGoal(quarterScores);
Console.WriteLine("Fourth quarter: " + quarterScores[3]);
void AddFieldGoal(int[] scores)
{
scores[3] = scores[3] + 3;
}
Fourth quarter: 10
No ref, and still the caller's array changed. That's because an array is a reference type. An int variable holds its number itself; types like that, int, decimal, bool and char, are value types. An array variable holds something else: the address of the array, where its values are kept in memory. Passing by value copies that address, like copying a house's address onto a second slip of paper. Two slips, one house: whoever goes there and repaints the front door changes the one house everyone visits.
But writing a new address on your slip doesn't move anyone else's house. Giving the parameter a whole new array changes only the method's copy of the address:
int[] quarterScores = { 12, 14, 6, 7 };
StartOver(quarterScores);
Console.WriteLine("First quarter: " + quarterScores[0]);
void StartOver(int[] scores)
{
scores = new int[] { 0, 0, 0, 0 };
Console.WriteLine("Inside the method: " + scores[0]);
}
Inside the method: 0
First quarter: 12
| Passed | What the method gets | Can it change the caller's variable? |
|---|---|---|
A value type, by value (int score) |
A copy of the value | No |
With ref (ref int score) |
The caller's variable itself | Yes |
With out (out int perPerson) |
The caller's variable, to set | Yes: it must set it |
An array, by value (int[] scores) |
A copy of the array's address | Its items, yes; which array the caller's variable holds, no |
Do it: add a snack to the bill
The snack stand's register keeps a running bill for each customer. Each time a customer adds a snack, the bill should grow by the snack's price times how many they're buying. The register calls the method like this:
decimal bill = 2.50m;
AddToBill(ref bill, 1.25m, 4);
The method gets three values:
billTotal: the customer's bill so far, adecimalpassed withref(2.50m).price: the price of one snack, adecimal(1.25m).quantity: how many of that snack the customer is buying, anint(4).
For example, a bill of $2.50, plus 4 packs of gum at $1.25 each:
| Bill so far | Price of one | How many | The bill after |
|---|---|---|---|
| $2.50 | $1.25 | 4 | $2.50 + 4 × $1.25 = $7.50 |
So after AddToBill(ref bill, 1.25m, 4), the caller's bill is 7.50m.
Your job: finish the method AddToBill(ref decimal billTotal, decimal price, int quantity). It returns nothing (void).
- Add the price times the quantity to
billTotal, so the caller's bill changes. - When the quantity is
0, the bill stays the same.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
By default a method gets copies, so it can't change your variables by accident. ref hands over the variable itself, out lets a method give back more than one answer, and an array's items can change through any copy of its address.