Method overloading

Two Fer
Two Fer in C#
public static class TwoFer
{
    public static string Speak()
    {
        return Speak("you");
    }

    public static string Speak(string name)
    {
        return $"One for {name}, one for me.";
    }
}

First, let's define the Speak() method that has a single parameter for the name:

public static string Speak(string name)
{
    return $"One for {name}, one for me.";
}

Within the method, we use string interpolation to build the return string where {name} is replaced with the value of the name parameter.

Then we define a second, parameterless method that calls the other Speak() method with "you" as its argument:

public static string Speak()
{
    return Speak("you");
}

The compiler will be able to figure out which method to call based on the number of arguments passed to the Speak() method.

Shortening

We can shorten the methods by rewriting them as expression-bodied methods:

public static string Speak() =>
    Speak("you");

public static string Speak(string name) =>
    $"One for {name}, one for me.";

or

public static string Speak() => Speak("you");

public static string Speak(string name) => $"One for {name}, one for me.";

String formatting

The string formatting article discusses alternative ways to format the returned string.

Optional parameters vs. method overloads

The main alternative to using method overloads is to use an optional parameter approach. If you're interested in how these two solutions compare to each other, go check out our optional parameters vs method overloads article.

24th Apr 2024 · Found it useful?