Optional Parameters in C# 4.0

In the last post we saw dynamic typed object in C# and as we saw earlier the upcoming features of C# 4.0, Today we are going to look at Optional Parameters.

Let’s say I have a class Employee and I provide few overloads of constructor to enable make certain parameters as optional as follows:

 public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Qualification { get; set; }
public string MiddleName { get; set; }

public Employee(string firstName, string lastName)
{
FirstName= firstName;
LastName= lastName;
Qualification= "N/A";
MiddleName= string.Empty;
}
public Employee(string firstName, string lastName, string qualification)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= string.Empty;

}
public Employee(string firstName, string lastName, string qualification,
string middleName)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= middleName
}
}

With C# 4.0, you need to create just one constructor for that and that is

public Employee(string firstName, string lastName,
string qualification = "N/A", string middleName = "")
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName = middleName;
}

as simple as that 🙂 and you can easily call that like Employee(“Adil”,”Mughal”);

This feature was available in some other languages but was for some reason not provided in C# till yet but now it’s available. This feature has good impact in COM interop which allows developers to skip missing parameters which we will hopefully see in later post(s). Finally, the compiler will always fill the optional parameters by their default given values, if you do not provide them. For instance, In our current case it will be:

Employee(“Adil”, “Mughal”, “N/A”, “”);

Simple but useful feature!