Methods: Parameters, Optional and Named Arguments, ref and out
Learn to write methods, use optional and named arguments, return several values with tuples, understand pass by value and the ref and out keywords, with a real program that proves each rule.
In this lesson you will
- Write and call methods
- Use optional and named arguments
- Return several values
- Explain pass by value, ref and out
About 28 minutes
One price rule for every screen
Omar’s price rule appears on the till screen, the receipt and the daily report, and a change should be made in one place. A method names a piece of logic and gives it parameters and a return value. C# methods can have optional parameters with default values, and callers can use named arguments to make a call readable. A method can return several values at once as a tuple, and C# calls the parameter passing by value unless you ask otherwise with ref or out.
For value types such as int, the method receives a copy, so changing the parameter does not change the caller’s variable. For reference types, the method receives a copy of the reference, so it can change the object that both point at, but cannot make the caller’s variable point at a different object. The keyword ref passes the variable itself, so assignments inside the method are visible to the caller. The keyword out is similar, but the method must assign it before returning, which is how methods such as int.TryParse give you both a success flag and a value.
| Feature | Example | Effect |
|---|---|---|
| Optional parameter | int Price(int cups, int unit = 320) | Callers may omit unit |
| Named argument | Price(unit: 250, cups: 3) | Order does not matter and the meaning is clear |
| Tuple return | (int total, int tax) Split(int x) | Two values from one call |
| ref | void Bump(ref int x) | The method changes the caller’s variable |
| out | bool TryParse(string s, out int v) | The method must assign v |
static int Price(int cups, int unit = 320, bool takeaway = false) => cups * unit + (takeaway ? 10 : 0);
static (int net, int tax) Split(int gross) { int net = gross * 100 / 119; return (net, gross - net); }
static void AddOne(int x) { x++; Console.WriteLine($"inside AddOne: {x}"); }
static void AddOneRef(ref int x) { x++; }
static void Fill(int[] a) { for (int i = 0; i < a.Length; i++) a[i] = 7; }
static void Replace(int[] a) { a = new[] { 9, 9, 9 }; Console.WriteLine($"inside Replace: {a[0]}"); }
int Calls = 0;
int Counted(int x) { Calls++; return x * 2; }
Console.WriteLine($"3 cups: {Price(3)}, 3 cups at 250: {Price(3, 250)}, named: {Price(unit: 250, cups: 2, takeaway: true)}");
var (net, tax) = Split(1190);
Console.WriteLine($"1190 gross splits into net {net} and tax {tax}");
int n = 5;
AddOne(n);
Console.WriteLine($"after AddOne: {n}");
AddOneRef(ref n);
Console.WriteLine($"after AddOneRef: {n}");
int[] data = { 1, 2, 3 };
Fill(data);
Console.WriteLine($"after Fill: {string.Join("", data)}");
Replace(data);
Console.WriteLine($"after Replace: {data[0]}");
Console.WriteLine($"TryParse good: {int.TryParse("42", out int ok)} -> {ok}; bad: {int.TryParse("4x2", out int bad)} -> {bad}");
Counted(1); Counted(2);
Console.WriteLine($"Counted ran {Calls} times");
3 cups: 960, 3 cups at 250: 750, named: 510
1190 gross splits into net 1000 and tax 190
inside AddOne: 6
after AddOne: 5
after AddOneRef: 6
after Fill: 777
inside Replace: 9
after Replace: 7
TryParse good: True -> 42; bad: False -> 0
Counted ran 2 times
The optional parameters worked as designed: Price(3) used the default unit price and gave 960, and Price(3, 250) gave 750. The named call put the arguments in a different order and gave 510, which is 2 x 250 plus the takeaway charge of 10, and shows why names make a call self-explanatory. The tuple return gave two values from one call: a gross of 1190 splits into a net of 1000 and a tax of 190, which is 19 percent of the net.
The pass-by-value rules show in the rest. AddOne changed its own copy, and afterwards n is still 5. AddOneRef received the variable itself, so n became 6. Fill changed the contents of the array that the caller also holds, so the caller sees 777. Replace made its parameter point at a new array of nines and printed 9 inside, but the caller’s array still starts with 7, because only a copy of the reference was passed. The TryParse calls show out parameters: the first succeeded with 42, and the second failed and left the out variable at its default of zero.
Check by hand: 3 x 320 = 960, 3 x 250 = 750, and 2 x 250 + 10 = 510. For the tax split, 1190 x 100 / 119 = 1000, and 1190 – 1000 = 190, which is 19 percent of 1000.
If a method must hand back a new value, return it, and use a tuple for several values. Reserve ref and out for the cases where they read naturally, such as TryParse.
Price(3, takeaway: true) is clearer than Price(3, 320, true). Names make calls readable without opening the method.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.
Practice
Write a method that returns the cheapest and the dearest price in an array as a tuple. Write a TryDiscount method with an out parameter that returns false for an unknown code. Call each from top-level statements and check the answers by hand.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does an optional parameter allow?
- The method to be private
- Callers may omit the argument
- Faster code
- Two return values
It has a default value.
What does a tuple return?
- Several values from one call
- Only text
- A file
- A class
(int net, int tax).
Does AddOne(n) change the caller’s n?
- No, a copy is passed
- Yes
- Only for ints over 5
- Only in loops
ref would change it.
Why does Fill change the caller’s array?
- Arrays are copied
- C# uses globals
- It is a bug
- Both refer to the same array
The reference was copied, not the array.
What must a method do with an out parameter?
- Read it first
- Ignore it
- Make it static
- Assign it before returning
The compiler checks this.
Summary
- Optional and named arguments make calls flexible and readable.
- Tuples return several values.
- Value types are copied; references are copied too, so contents can change but the variable cannot be re-pointed.
- ref and out pass the variable itself.
Questions
What is an expression-bodied method?
A method written with => and a single expression, as in int Double(int x) => x * 2.
What is a local function?
A method declared inside another method, as the examples above do with static functions. It keeps helpers close to where they are used.
Can I overload methods?
Yes. Several methods can share a name with different parameter lists.
