Optional Parameters
One of the major features in C# 4.0 is optional parameters. You can define the methods with any number of optional parameters. When you define an optional parameter, specify the default value for the same.
In the following example, we have a method called Optional with three parameters a,b and c.
As part of method definition, b and c is having default values associated with it. These two parameters are treated as optional parameters; means, when you access the method there is no need to pass the value for these two parameters.
From main, we are calling the same method using three different combination of parameters. First call, passes values for all three parameters, second passes only two values corresponding to a and b. In second call parameter c will take the default value. In the last call, only value for a is passes; b and c will take the default values associated with it.
static void Main(string[] args)
{
Optional(1, 2, 3);
Optional(2, 3);
Optional(4);
Console.Read();
}
public static void Optional(int a, int b = 20, int c = 40)
{
int sum = a + b + c;
Console.WriteLine(“Sum {0}”, sum);
}
Result:
Sum 6
Sum 45
Sum 64
Named arguments is another C# 4.0 feature, which will be covered in the next post. Optional parameters along with Named arguments help in better usage of method arguments.