By default, each parameter of a method is required, but in C# 4.0, Microsoft introduces optional parameters. So in this post, you’ll learn what is an optional parameter in C#. And how can you create and use optional parameters in C#?
In C# 4.0, an optional parameter was introduced. The optional parameter in C# is the way to specify the parameters that are required but with the default values. If you do not pass the argument value at the method calling time, then the method uses its default argument values which we specified in the optional parameter.
Here is an example of Optional Parameters in C#
using System;
namespace Program
{
public class Program
{
//Optional Parameter in c#
static void MethodWithDefaultParameter(int value = 1, string name = "Default Value")
{
Console.WriteLine("value = {0}, name = {1}", value, name);
}
public static void Main()
{
// Omit the optional parameters.
MethodWithDefaultParameter();
// Omit second optional parameter.
MethodWithDefaultParameter(4);
// You can't omit the first but keep the second.
// Method("Dot");
// Classic calling syntax.
MethodWithDefaultParameter(4, "Tutorialsrack");
// Specify one named parameter.
MethodWithDefaultParameter(name: "Satya Nadella");
// Specify both named parameters.
MethodWithDefaultParameter(value: 5, name: "Sundar Pichai");
Console.ReadLine();
}
}
}
value = 1, name = Default Value
value = 4, name = Default Value
value = 4, name = Tutorialsrack
value = 1, name = Satya Nadella
value = 5, name = Sundar Pichai
In addition, to complement the optional parameters, it is possible explicitly to specify parameter names in method calls. It makes your code more readable and clean. By specifying the parameter name, you can reorder the parameters in the parameter lists of called methods
The only restriction is that named parameters must be placed after the unnamed parameters. Parameter names can be specified for both optional and required parameters and can be used to improve readability or arbitrarily to reorder arguments in a call.
I hope this article will help you to understand what is an optional parameter in C#. And how can you create and use optional parameters in C#?
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments