Skip to content
Codewilds

Lesson 10 of 34 · Methods

C# Method Overloading, Optional and out Parameters

medium20 XP3 min read

The methods you wrote in the last lesson took a fixed list of inputs and returned one value. C# gives methods much more flexibility: one name can have several versions, parameters can be optional, callers can name their arguments, and a method can hand back extra results through out parameters.

Overloading

Two methods may share a name if their parameter lists differ in number or types. The compiler picks the right one from the arguments:

public static int Max(int a, int b) => a > b ? a : b;
public static int Max(int a, int b, int c) => Max(Max(a, b), c);
public static double Max(double a, double b) => a > b ? a : b;

Max(3, 9);        // first version → 9
Max(3, 9, 4);     // second version → 9
Max(2.5, 1.0);    // third version → 2.5

Console.WriteLine is heavily overloaded — that is why it accepts strings, numbers and bools. Note that the return type alone does not count: two methods that differ only in what they return will not compile.

Optional parameters and named arguments

A parameter with a default value is optional. Optional parameters must come after the required ones:

public static string Attack(string weapon, int damage = 10, bool critical = false)
{
    int total = critical ? damage * 2 : damage;
    return $"{weapon} hits for {total}";
}

Attack("Sword");                    // "Sword hits for 10"
Attack("Axe", 15);                  // "Axe hits for 15"
Attack("Bow", critical: true);      // "Bow hits for 20" — named argument

Named arguments (critical: true) let you skip optional parameters and make calls with many bools readable.

params: any number of arguments

Mark the last parameter params and callers can pass a comma-separated list instead of an array:

public static int Total(params int[] values)
{
    int sum = 0;
    foreach (int v in values) sum += v;
    return sum;
}

Total(1, 2, 3);   // 6
Total();          // 0

out parameters and the TryParse pattern

A method can only return one value. When it needs to report success and a result, C# uses out parameters. The method must assign every out parameter before it returns, and the caller marks the argument with out too:

if (int.TryParse("42", out int number))
{
    Console.WriteLine(number + 1);   // 43
}

bool ok = int.TryParse("forty-two", out int bad);   // false, bad is 0

int.TryParse never throws an error for bad input; it simply returns false. You can write your own methods in the same style:

public static bool TryDivide(int a, int b, out int result)
{
    if (b == 0)
    {
        result = 0;
        return false;
    }
    result = a / b;
    return true;
}

(There is also ref, which passes a variable the method can read and change. out is far more common.)

Common mistakes

  • Optional before required: void F(int a = 1, int b) does not compile.
  • Forgetting to assign an out parameter on one of the paths — the compiler reports CS0177.
  • Ambiguous overloads: F(int a, double b) and F(double a, int b) called as F(1, 2) confuse the compiler.

Assignment

Complete the methods in Program:

  1. Two overloads of Area (both are already declared): Area(radius) returns the area of a circle (Math.PI * r * r), and Area(width, height) returns the area of a rectangle.
  2. Greet(name, greeting = "Hello", shout = false) returns "Hello, Ann!"; with a custom greeting "Hi, Bo!"; and when shout is true the whole text is uppercase: "HELLO, ANN!".
  3. Sum(params int[] numbers) returns the total of all arguments (0 for none).
  4. TryParseCoordinate(text, out x, out y) parses text like "3,4" or " -2 , 7 ". It returns true and sets x and y on success; for anything else ("3", "a,b", "1,2,3") it returns false with x and y set to 0.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Function parameters in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 10 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.