Methods: The Kitchen Recipe

Methods: The Kitchen Recipe in C#: A method is a recipe card. It has a name you can call it by, a list of ingredients it expects (the parameters), a statement…

The Analogy: The Recipe Card

A method is a recipe card. It has a name you can call it by, a list of ingredients it expects (the parameters), a statement of what it yields (the return type), and the steps in between. Once the card is written, nobody needs to remember the steps — they just say "make the béchamel" and get a béchamel.

Two properties make a recipe worth writing down. It is reusable: three dishes can call for the same sauce. And it is testable in isolation: you can taste the sauce before it goes anywhere near the pie. A hundred-line Main has neither property, which is the practical argument for breaking work into methods long before the code gets big enough to force it.

The best recipes also have no hidden effects. Given the same ingredients they produce the same result and change nothing else in the kitchen. Methods like that are the ones you can reason about at a glance, and most of this lesson is about how to write them.


Syntax or Core Structure

using System;

class Program
{
    static int Add(int a, int b)
    {
        return a + b;
    }

    static double Average(int total, int count) =>
        count == 0 ? 0 : (double)total / count;

    static void Log(string message)             // void: returns nothing
    {
        Console.WriteLine($"[log] {message}");
    }

    static string Describe(string name, int qty = 1, string unit = "box") =>
        $"{name} x{qty} [{unit}]";

    static int Sum(params int[] numbers)
    {
        int total = 0;
        foreach (int n in numbers) total += n;
        return total;
    }

    static void Main()
    {
        Log("starting");
        Console.WriteLine(Add(2, 3));
        Console.WriteLine(Average(7, 2));
        Console.WriteLine(Describe("bolts", 4));
        Console.WriteLine(Describe("crate"));
        Console.WriteLine(Describe(name: "nuts", unit: "bag", qty: 2));
        Console.WriteLine(Sum(1, 2, 3, 4));
        Console.WriteLine(Sum());
    }
}

Output:

[log] starting
5
3.5
bolts x4 [box]
crate x1 [box]
nuts x2 [bag]
10
0

The declaration reads left to right as modifiers, return type, name, parameters. static means the method belongs to the type rather than to an object of that type, which is why Main can call it without creating a Program; Module 4 deals with the alternative.

Average uses an expression body (=>), which is shorthand for a method whose entire body is one return. It is not a lambda and it is not slower; it is the same method written with less punctuation.

Describe shows optional parameters and named arguments together. Defaults let one method serve three call shapes, and naming the arguments means they no longer need to be in order — Describe(name: "nuts", unit: "bag", qty: 2) skips over qty and comes back to it.

Sum(params int[] numbers) accepts any number of arguments, including none, in which case it receives an empty array rather than null.


Technical Depth: Signatures, Overloads and Scope

What the compiler considers the signature

The signature is the name plus the number, types and modifiers of the parameters. The return type is not part of it, which is why these two cannot coexist:

static int  Parse(string s) { ... }
static long Parse(string s) { ... }   // ERROR: same signature

Overloading means several methods sharing a name with different parameter lists:

static decimal Total(decimal price) => price;
static decimal Total(decimal price, int qty) => price * qty;
static decimal Total(decimal price, int qty, decimal discount) => price * qty - discount;

Overload resolution picks the best match at compile time, preferring an exact type match over one that needs a conversion. When two candidates are equally good the compiler reports ambiguity rather than guessing.

Optional parameters versus overloads

// library v1
public static string Format(string s, int width = 10) { ... }

The default is baked into the call site at compile time: a caller that wrote Format("x") has 10 compiled into their assembly. Ship v2 with width = 20 and that caller keeps passing 10 until it is rebuilt. Inside one project this never matters; across a package boundary it is a real versioning hazard, which is why public libraries tend to prefer overloads.

Optional parametersOverloads
Call sitesone method to documentone per shape
Default value livesin the callerin the callee
Safe to change laterno, across assembliesyes
Works with interfacesawkwardlynaturally

Local functions

static decimal Invoice(decimal[] amounts)
{
    static decimal WithVat(decimal a) => a * 1.20m;    // static: captures nothing

    decimal total = 0m;
    foreach (decimal a in amounts) total += WithVat(a);
    return total;
}

A local function is a method declared inside another method. Use one when a helper is meaningful only to its host — it keeps the class's surface small, and marking it static documents that it captures no local state. Unlike a lambda it has a name, can be recursive, and allocates nothing.

Recursion, and its ceiling

static long Factorial(int n)
{
    if (n < 0) throw new ArgumentOutOfRangeException(nameof(n));
    if (n <= 1) return 1;              // base case - not optional
    return n * Factorial(n - 1);
}

Every recursive call takes a stack frame, and the stack is about 1 MB by default. Omit the base case and you get a StackOverflowException, which — unlike almost every other exception in .NET — cannot be caught: the process dies immediately. C# does not guarantee tail-call optimisation, so deep recursion over a large list should be rewritten as a loop.

Guarding the inputs

static decimal PricePerUnit(decimal total, int units)
{
    ArgumentNullException.ThrowIfNull(nameof(total));   // for reference types
    if (units <= 0)
        throw new ArgumentOutOfRangeException(nameof(units), units, "must be positive");

    return total / units;
}

A method that validates its arguments and throws with nameof gives a stack trace that names the caller's mistake. The alternative — returning 0 or -1 for bad input — pushes the failure somewhere far away from its cause.

Documenting the recipe

/// <summary>Splits a total evenly, discarding any remainder.</summary>
/// <param name="units">How many ways to split; must be positive.</param>
/// <returns>The amount per unit.</returns>
/// <exception cref="ArgumentOutOfRangeException">units is zero or negative.</exception>
public static decimal PricePerUnit(decimal total, int units) => total / units;

Those /// comments become IntelliSense tooltips and can be compiled into a documentation file. They are worth writing on anything public and a waste of keystrokes on a private helper whose name already says everything.


Real World Example: An Invoice, One Rule Per Method

The same calculation written as one long Main is perfectly correct and nearly unreviewable. Split by rule, each line of the total can be checked on its own.

using System;

class Program
{
    const decimal VatRate = 0.20m;

    static decimal LineTotal(int qty, decimal unitPrice) => qty * unitPrice;

    static decimal Discount(decimal subtotal) => subtotal switch
    {
        >= 500m => subtotal * 0.10m,
        >= 200m => subtotal * 0.05m,
        _       => 0m,
    };

    static decimal Vat(decimal amount) =>
        Math.Round(amount * VatRate, 2, MidpointRounding.AwayFromZero);

    static string Money(decimal amount) => amount.ToString("F2");

    static void PrintRow(string label, decimal amount) =>
        Console.WriteLine($"{label,-12}{Money(amount),10}");

    static void Main()
    {
        (string name, int qty, decimal price)[] lines =
        {
            ("bracket",  30, 4.75m),
            ("bolt",    250, 0.35m),
            ("nut",     480, 0.20m),
        };

        decimal subtotal = 0m;

        foreach (var l in lines)
        {
            decimal value = LineTotal(l.qty, l.price);
            subtotal += value;
            PrintRow(l.name, value);
        }

        decimal discount = Discount(subtotal);
        decimal net = subtotal - discount;
        decimal vat = Vat(net);

        Console.WriteLine(new string('-', 22));
        PrintRow("subtotal", subtotal);
        PrintRow("discount", -discount);
        PrintRow("net", net);
        PrintRow("VAT 20%", vat);
        PrintRow("total", net + vat);
    }
}

Output:

bracket         142.50
bolt             87.50
nut              96.00
----------------------
subtotal        326.00
discount        -16.30
net             309.70
VAT 20%          61.94
total           371.64

Checking the arithmetic: 30 × 4.75 = 142.50, 250 × 0.35 = 87.50 and 480 × 0.20 = 96.00 give a subtotal of 326.00. That clears the 200 threshold but not 500, so the discount is 5% — 16.30 — leaving a net of 309.70. VAT at 20% is 61.94, and the total is 371.64.

Discount is the rule most likely to change, and it is four lines you can read without reading anything else. A tester can call it with 199.99, 200.00, 499.99 and 500.00 and prove the boundaries without constructing an invoice at all. That is the payoff of extracting a method: the rule becomes addressable.

LineTotal, Vat and Money take values and return values. None of them writes to a field, prints anything or reads the clock, so each one is a single Assert.Equal away from being tested.

PrintRow is the only method that touches the console, so all the formatting lives in one place. Changing the column widths is a one-line change; if the WriteLine calls had been spread through Main it would be five.

Vat names its rounding rule. MidpointRounding.AwayFromZero is a tax decision, not a technical one, and putting it inside a method called Vat is how that decision survives the next refactor.


Common Mistakes

  1. Not returning on every path. if (x > 0) return 1; with nothing after it is CS0161, "not all code paths return a value". Either add a final return or throw, and prefer the throw when the case really is impossible.
  2. Discarding the result of a pure method. name.Trim(); and Math.Round(x, 2); compute an answer and drop it, because strings and numbers are immutable. Assign it: name = name.Trim();.
  3. Trying to overload on the return type. Two methods differing only in what they return will not compile. Give them different names — ParseInt and ParseLong — or different parameters.
  4. Assuming a changed default reaches existing callers. Optional-parameter defaults are compiled into the caller, so a library's new default only applies after every consumer is rebuilt. Add an overload instead.
  5. Recursion without a base case. The result is StackOverflowException, and it cannot be caught or logged: the process is killed. Write the base case first, before the recursive step.
  6. One method doing two jobs. CalculateAndSaveInvoice cannot be tested without a database and cannot be reused without saving. Split the calculation from the effect.
  7. A parameter list of anonymous booleans. Export(true, false, true) tells a reader nothing. Use named arguments at the call site, or an options object, or an enum.
  8. Reaching for a field instead of a parameter. A method that quietly reads mutable state gives different answers on different days. Pass what it needs and return what it computed.

Best Practices

  • Give each method one job and a name that says it: a verb phrase such as CalculateVat, TryParseRow, SaveInvoice. If the name needs an "And", it is two methods.
  • Prefer returning a value to mutating one. Pure methods are trivial to test, safe to call twice, and safe to call from several threads.
  • Validate arguments at the top and throw ArgumentException family exceptions with nameof, so failures name the parameter that was wrong.
  • Keep the parameter list short. Past three or four, group them into a record — which Module 8 covers — rather than adding another positional argument.
  • Use named arguments at call sites whose meaning is otherwise invisible, especially for bool flags and for methods with several same-typed parameters.
  • Use expression bodies for genuine one-liners and a braced body as soon as there is a second statement. Do not compress a real method into one dense expression.
  • Prefer a local function for a helper used once inside a single method, and mark it static when it needs nothing from its host.
  • Write /// documentation on anything public, including what it throws. Private helpers should be self-explanatory from the name instead.

Practice Exercises

  1. Write static bool IsPalindrome(string text) that ignores case and non-letter characters, plus a small Main that tests it against "Never odd or even", "C# rocks" and "". Keep the method free of Console calls.
  2. Write three overloads of Total — (decimal price), (decimal price, int qty) and (decimal price, int qty, decimal discount) — then rewrite them as a single method with optional parameters. Note one advantage of each version.
  3. Refactor the invoice example so the VAT rate and the two discount thresholds are parameters of a static Invoice Calculate(...) method rather than constants, and print two invoices with different rates from one run.
  4. Implement static long Fib(int n) recursively, then iteratively, and print both results for n = 0..20 side by side. Time each with Stopwatch for n = 32 and explain the difference.