Optional Parameters in C#

Optional Parameters

If you’re of the same mind, then you’ll probably be pleased that C# 4.0 supports optional parameters.
For many C# developers, the long wait for optional parameters is over with C# 4.0. An optional parameter lets you provide a default value and the caller has a choice of whether or not they want to provide an argument. In current and earlier versions of C#, you could simulate optional parameters like this:
// Overload with no parameter
public static string SayHello()
{
    return "Hey, You!";
}
    
// Overload with normal parameter
public static string SayHello(string name)
{
    return "Hey, " + name + "!";
}
The SayHello method above is overloaded with both an empty parameter list and a parameter list with a single string parameter. To the user of this code, the name parameter appears to be optional and both of the following calls work fine:
// Name is optional
var greetYou = SayHello();
    
// Can provide name if you want
var greetJoe = SayHello("Joe");
If you had methods with more parameters and wanted to provide a more flexible coding experience, you would provide more overloads. Many developers have said that this is cumbersome and leaves more code to maintain. If you’re of the same mind, then you’ll probably be pleased that C# 4.0 supports optional parameters. The snippet below shows an optional parameter, replacing the previous two overloads:
// Method with optional parameter
public static string SayHello(string name = "You")
{
    return "Hey, " + name + "!";
}
As shown in the previous snippet, the syntax to call an optional parameter requires assigning a default value to the parameter. In the listing above, "You" will be assigned to name if the caller does not provide a value.

No comments:

Post a Comment