Monday, June 22, 2009

C# 4.0 -Optional Parameters

I was really excited, when i have seen upcoming feature in c# 4.0, After come across some article, This feature will be very useful.


Optional Parameters

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

Older Method

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
}
}

Newer Method

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