Lesson 11 of 24
In progress
Methods and parameters
Write methods with clear signatures, use optional and named arguments, and know when out and ref are worth the trouble.
A method names a piece of work and fixes its inputs and output. Most design decisions in a small program are really decisions about method signatures.
What you will learn
- Declare methods with parameters, defaults and return values.
- Use named arguments and
paramsat the call site. - Decide between
out,refand returning a tuple.
The declaration
static decimal WithTax(decimal amount, decimal rate = 0.18m)
{
return Math.Round(amount * (1 + rate), 2);
}
Console.WriteLine(WithTax(1200m)); // 1416.00
Console.WriteLine(WithTax(1200m, 0.05m)); // 1260.00
static means the method belongs to the type, not an instance. The default value makes the common call short, and it must come after all required parameters.
Defaults are compiled into the caller. If a library changes a default, callers that were compiled against the old value keep using it until they recompile, which is why defaults are safer for application code than for public libraries.
Expression-bodied methods
static decimal WithTax(decimal amount) => Math.Round(amount * 1.18m, 2);
static string Describe(int n) => n > 0 ? "positive" : "not positive";
=> replaces a body with a single expression. For a one-line calculation it reads better than braces; for anything with a branch or a loop, use a block.
Named arguments
Send(to: "ana@example.com", subject: "Invoice", body: "Attached.");
Named arguments document a call with several parameters of the same type, and they let you skip optional ones. They are most valuable where two strings or two numbers appear in a row, since the compiler cannot catch a swap.
params
static int Sum(params int[] values)
{
int total = 0;
foreach (int value in values) total += value;
return total;
}
Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum());
params collects the arguments into an array. It is convenient for a small helper and easy to overuse: as soon as the method has other parameters, or the caller passes a collection, an explicit array is clearer.
out and ref
static bool TryDivide(decimal total, decimal parts, out decimal result)
{
if (parts == 0)
{
result = 0m;
return false;
}
result = total / parts;
return true;
}
out means the method assigns the parameter, and the caller must declare it at the call site:
if (TryDivide(100m, 4m, out decimal unit))
{
Console.WriteLine(unit);
}
The Try... pattern returns a bool for success and the value through out, which avoids exceptions for expected failures. int.TryParse and Dictionary.TryGetValue follow the same shape.
ref means the method may read and write the caller’s variable. It is rarer, harder to reason about, and usually replaceable by returning a value.
Modern C# often prefers a tuple:
static (bool ok, decimal value) Divide(decimal total, decimal parts) =>
parts == 0 ? (false, 0m) : (true, total / parts);
var (ok, value) = Divide(100m, 4m);
A tuple makes both results explicit and deconstructs at the call site, which is easier to follow than an out parameter whose scope leaks into the caller.
Overloading
static string Format(decimal amount) => amount.ToString("F2");
static string Format(decimal amount, string currency) => $"{currency} {amount:F2}";
Overloads must differ in parameter types or count, not return type. The compiler picks the best match, and ambiguity is a compile error rather than a guess.
Keep overloads for the same operation with different inputs. When the behaviour differs meaningfully, a different name is clearer, and a boolean parameter that switches behaviour is the worst version of both.
Local functions
static int CountWords(string text)
{
return text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Count(IsWord);
static bool IsWord(string s) => s.Any(char.IsLetter);
}
A local function keeps a helper close to its only caller and can capture locals. It is a good alternative to a private method used once, and a good way to keep the main method readable.
Method length and naming
A method that fits on one screen can be checked by reading it. Beyond that, extract the blocks that have a clear purpose and name them.
Name methods with verbs: CalculateTotal, SendInvoice, IsEligible. A name that needs "and" describes two methods. A name that lies about a side effect — GetUser that writes a log row and sends an email — is worse than a long name.
Return early for guards, keep the happy path unindented, and prefer returning a value to mutating a parameter. Those three habits cover most of what makes a method easy to test.
Using a boolean parameter to switch between two behaviours, such as Format(amount, true). The call site does not say what true means. Two named methods are clearer.
Write a method that takes a list of prices and a discount percentage, validates the percentage, and returns the total after discount, with the discounted amount as a second value.
Show solution
static (decimal total, decimal saved) ApplyDiscount(IReadOnlyList<decimal> prices, int percent) { if (percent is < 0 or > 100) throw new ArgumentOutOfRangeException(nameof(percent), "must be 0-100"); decimal total = prices.Sum(); decimal discount = Math.Round(total * percent / 100m, 2); return (total - discount, discount); } var (total, saved) = ApplyDiscount(new[] { 100m, 250m }, 10); Console.WriteLine($"{total:F2} after saving {saved:F2}"); The tuple returns both numbers a caller needs, without an out parameter or a second method. ArgumentOutOfRangeException names the bad parameter, and nameof keeps the message correct if the parameter is renamed.
Recap
- Defaults shorten calls; named arguments make multi-parameter calls readable.
Try...withoutavoids exceptions for expected failures; a tuple is often clearer thanout.- Keep methods short, name them after the operation, and do not hide side effects.
Module 3 covers objects: classes, constructors, properties, inheritance and interfaces.
Can a method return multiple values?
What is the difference between out and ref?
Progress is saved in this browser only. No account, no email.