Methods, parameters & overloads
A method groups behavior behind a name and parameter list. Parameters are passed by value by default. For a class instance this means the method receives a copy of the reference: it can mutate the referenced object, but it cannot replace the caller's variable unless the parameter variable itself is passed by reference.
ref, out and in
refpasses an existing variable by reference; it must already be assigned.outpasses by reference and requires the called method to assign a value before returning.inpasses by reference but prevents reassignment through that parameter.
static bool TryParsePort(string text, out int port)
{
return int.TryParse(text, out port) && port is > 0 and <= 65535;
}
if (TryParsePort("8080", out var port))
{
Console.WriteLine(port);
}Overloading and optional parameters
Methods can share the same name when their parameter signatures differ. Return type alone cannot distinguish overloads. Optional parameters define defaults, while named arguments make the meaning of call-site values explicit.
static decimal Total(decimal price, int quantity = 1) => price * quantity;
Console.WriteLine(Total(12.5m));
Console.WriteLine(Total(price: 12.5m, quantity: 2));Key points
- Default parameter passing is by value, including a copied reference for reference types.
ref,outandinchange how the parameter variable itself is passed.- Overloads must differ by parameter signature; return type alone is insufficient.