How to minimize the Method Overloading in C# 4.0

We can avoid creating many overloads of a method by specifing default values for some parameters.

public static void EmployeeDetails(int empId, string address="BBSR", double salary=15000)

{ }

static void Main(string[] args)

{

EmployeeDetails(1);

EmployeeDetails(1, "Cuttack");

EmployeeDetails(1, "Cuttack", 20000);

}

In the above Example there is a method called EmployeeDetails which has 3 parameters including 2 default parameters having certain values. This leads to the concept of optional parameters which means without giving those optional parameters we will be able to call the method like above. This provides a flexibility towards avoiding method overloading.

There is a new feature of C# 4.0 to call the methods with there parameters names, so that the actual order of the parameters doesn’t matter. No need to worry about remembering the sequence of parameters in the methods. This is very nice feature of Named parameters. So you can call the above method like below :

EmployeeDetails(empId: 1, address : "Cuttack", salary: 20000);

EmployeeDetails(salary: 20000, address : "Cuttack",empId: 1);

EmployeeDetails(address : "Cuttack", salary: 20000, empId: 1);

EmployeeDetails(empId: 1);

The above given approach of calling the Method has no difference for getting the Method to be called.

And Named Parameters provide more flexibility for using the optional parameters. You can skip the Optional parametes and call the method by passing the Named Parameters.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!