Monday, September 12, 2011

Named and Optional Parameters C# 4.0 Feature

Optional parameter and name parameters are 2 different features in c# 4.0.

let us first discuss optional parameters.
let us consider we have write few method to add 2,3 and 4 numbers.

what we used to this is writing overload method with same name and different parameters.

some thing like this
public int Add(int a, int b)
{
//logic
}
public int Add(int a, int b, int c)
{
//logic
}
public int Add(int a, int b, int c, int d)
{
//logic
}

Now with optional parameters we can simple write one single method to handle this method over loading situation


public int Add(int a, int b, int c = 0, int d = 0)
{
}


in the above code we have given default values to c and d means while calling this method if we don't pas parameter for c and d then 0 will be consider as default value so here C and D are optional parameters.

Add(1, 2); //c and d are optional
Add(1, 2, 3); // d is optional
Add(1, 2, 3, 4);

Coming to named parameters

let us consider we are creating employee details

public void CreateEmployee(string name, int age = 22,string address = "Not specified");

with named parameters we call call this method irrespective of order of the parametes

CreateEmployee("Venkatesh", age: 28);
CreateEmployee(address: "Hyderabad", name: "Venkatesh");

No comments:

Post a Comment