Introduction
C#4.0 has bring the new Optional Parameter in its collection to give developers the flexibility passing parameters at their discretion.
Background:
Consider the below example which is done in C#3.0
class Program
{
static void Main(string[] args)
{
WithoutNamedParameter(null,null); WithoutNamedParameter("Some Name", null); WithoutNamedParameter(null, 25); WithoutNamedParameter("Some Name", 50);
Console.ReadKey(true);
}
private static void WithoutNamedParameter(string name, int? age)
{
string _name = "Default Name";
int? _age = 18;
if (!string.IsNullOrEmpty(name)) _name = name;
if (age.HasValue) _age = age;
Console.WriteLine(string.Format("{0},your age is {1}", _name, _age));
}
}
In the WithoutNamedParameter method first we have assigned two default values to the two variables _name and age. Then we are checking, if the Calling function has assigned any value to the method parameters or not and depending on that, we are displaying the values.
Next have a look at the calling function. The method WithoutNamedParameter has been called four times with four different values. But the code looks pretty ugly.
Another option was to create four overloaded method to satisfy the requirement if the Empty or Null checking needs to be avoided which on the other hand was again a tedious job.
The new Optional Parameter, introduced with C#4.0 has a better look.
Optional Parameters
Consider the below program written in C#4.0
class Program
{
static void Main(string[] args)
{
MethodWithOptionalParameters();
MethodWithOptionalParameters("Some Name");
MethodWithOptionalParameters(Age: 25);
MethodWithOptionalParameters("Some Other Name", 20);
Console.ReadKey(true);
}
private static void MethodWithOptionalParameters
(string Name = "Default Name", int Age = 18)
{
Console.WriteLine(string.Format("{0}, your age is {1}",Name,Age));
}
}
As can be observed that first of all in the new code we are no longer checking the Empty/Null values of the method parameters. Instead , we have assigned the default values to the method parameters.
Consider the First Calling Method. We are not at all passing any parameter. The complier will happily compile though (which was not the case in the earlier example as it would have reported the error No overload for method 'WithoutNamedParameter' takes '0' arguments.
The IL for the code is depicted below
Which indicates that the Optional Parameter is in the MSIL.
Consider the third Method call
MethodWithOptionalParameters(Age: 25);//Ask to print only Name
Here we are specifying the Age only which is a Named Parameter in this case and the complier will understand that and will do the favour./p>
The final output being
Conclusion:
In this short article we have seen how optional parameter help developers to avoid writing overloaded methods and rather helps in code reusability.
Comments on the topic are highly appreciated for the improvement of the topic.
Thanks for reading the article.