Lesson 5 / 25
Methods and Parameters
Define methods with optional, named, ref, out, in and params parameters.
How arguments are passed
Methods take parameters by value by default: the method gets a copy of a value type, or a copy of the reference for a reference type (so it can modify the object, but not make the caller's variable point elsewhere). Modifiers change that. ref passes the variable itself, so the method can reassign it. out is like ref but the method must assign it, used by the TryParse pattern. in passes by reference read-only, useful for large structs. params accepts a variable number of arguments (C# 13 extended it to collection types such as params ReadOnlySpan<T>). Parameters can have default values, and callers can use named arguments for clarity. Short methods can be expression-bodied (=>), and local functions declared inside a method keep helper logic close to where it is used.
Common parameter patterns
TryParse with out avoids exceptions for expected bad input.
if (int.TryParse("42", out int value))
{
Console.WriteLine(value + 1);
}
void Swap(ref int a, ref int b) => (a, b) = (b, a);
int x = 1, y = 2;
Swap(ref x, ref y); // x = 2, y = 1
decimal Total(decimal price, int qty = 1, decimal discount = 0m) =>
price * qty * (1 - discount);
var t = Total(499m, discount: 0.1m); // named argument skips qty
int Sum(params int[] numbers)
{
int total = 0;
foreach (var n in numbers) total += n;
return total;
}
Console.WriteLine(Sum(1, 2, 3));Photocopy versus the original file
Passing by value hands the method a photocopy: scribbles do not reach your original. ref hands over the original file itself, so whatever the method writes, you see.
Quick check: Which modifier requires the called method to assign the parameter before returning?
- ref
- out
- in
- params
Answer
out — out parameters must be definitely assigned by the method, as in TryParse.