Lesson 10 — Reusable Logic

Methods

C# methods add optional parameters, named arguments, expression bodies, and out/ref parameters over Java's approach — making common patterns more concise.

CSHARP — Methods
// Expression-bodied — no braces for single expressions:
static int Add(int a, int b) => a + b;
static string Greet(string name) => $"Sawubona, {name}!";

// Standard with multiple statements:
static void PrintReport(string name, double mark) {
    string grade = mark >= 50 ? "Pass" : "Fail";
    Console.WriteLine($"{name}: {mark:F1}% — {grade}");
}

// Usage:
Console.WriteLine(Add(45, 30));     // 75
Console.WriteLine(Greet("Thandi")); // Sawubona, Thandi!
PrintReport("Sipho", 74.5);

Optional and Named Parameters

C# supports default parameter values — callers can omit them. Named arguments let callers specify parameters by name in any order.

CSHARP — Optional and named
static void RegisterLearner(
    string name,
    string course  = "Undecided",
    int    year    = 1,
    bool   hasLaptop = false) {
    Console.WriteLine($"{name} | {course} | Year {year} | Laptop: {hasLaptop}");
}

RegisterLearner("Thandi");                          // uses all defaults
RegisterLearner("Sipho", "Java");                   // overrides course
RegisterLearner("Lerato", year: 2, name: "Lerato"); // named — order doesn't matter
RegisterLearner("Bongani", hasLaptop: true, course: "SQL");

out Parameters

out parameters return multiple values from a method — the most common use is TryParse patterns.

CSHARP — out parameters
// Declaring a method with out:
static bool TryDivide(int a, int b, out double result) {
    if (b == 0) { result = 0; return false; }
    result = (double)a / b;
    return true;
}

// Calling with out:
if (TryDivide(10, 3, out double quotient))
    Console.WriteLine($"Result: {quotient:F4}"); // 3.3333
else
    Console.WriteLine("Division by zero.");

// Inline out variable declaration:
if (int.TryParse("42", out int parsed))
    Console.WriteLine($"Parsed: {parsed}");

Practice Task

Your Turn

Write a static class MathUtils with: Max(int a, int b), Clamp(int value, int min, int max), IsPrime(int n) returning bool, Statistics(int[] values, out double mean, out int min, out int max) using out parameters. Test all from Main.

Common Mistakes

  • Optional parameters must come after required parameters.
  • out parameters must be assigned before the method returns.
  • => not -> for expression bodies.
  • Method names are PascalCase in C#.

Professional Tip

Named arguments are especially useful when calling methods with many bool parameters — Send(true, false, true) is unclear; Send(retry: true, async: false, log: true) is self-documenting.

Mini Quiz

What does an expression-bodied method use instead of braces?