← C# from Scratch Lesson 25 of 39 · 10 XP

Method overloading

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Overloading means several methods with the same name but different parameters (in number or type). The compiler picks the right one from the arguments:

static class Calc
{
    public static int Add(int a, int b) => a + b;
    public static double Add(double a, double b) => a + b;
    public static int Add(int a, int b, int c) => a + b + c;
}

Calc.Add(1, 2);        // the int version
Calc.Add(1.5, 2);      // the double version: 2 is widened to double
Calc.Add(1, 2, 3);
  • You can't overload by the return type alone — from the call Add(1, 2) you couldn't tell which one is needed.
  • It's class methods that get overloaded. Local functions (methods right in the file, as in the previous lessons) can't be overloaded — you'd get error CS0128, so here the methods live in a static class (a "box" class for methods), and public makes them visible outside.
  • Console.WriteLine is itself an example of overloading: it has versions for int, string, double, bool…

Task. Add three overloads of Describe to the Printer class: for int — int: <x>, for double — double: <x> (two decimal places), for string — string: <s> (<length>).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.