Visit the two-fer exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Optional parameter
Optional parameter
public static class TwoFer
{
public static string Speak(string name = "you")
{
return $"One for {name}, one for me.";
}
}
We define a single Speak() method with one optional parameter: name.
This optional parameter has its default value set to the string "you".
The caller of a method with an optional parameter can either pass in a value (which is then used) or not pass in a value (which caused the default value to be used).
These calls are thus identical:
`Speak()`
`Speak("you")`
Within the method, we use string interpolation to build the return string where {name} is replaced with the value of the name parameter.
Shortening
We can shorten the method by rewriting it as an expression-bodied method:
public static string Speak(string name = "you") =>
$"One for {name}, one for me.";
or
public static string Speak(string name = "you") => $"One for {name}, one for me.";
The string formatting article discusses alternative ways to format the returned string.
Optional parameters vs. method overloads
The main alternative to using an optional parameter is to use a method overloading approach. If you’re interested in how these two solutions compare to each other, go check out our optional parameters vs method overloads article.
Method overloading
Method overloading
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.";
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.
Source: Exercism csharp/two-fer