New feature "Optional parameters" in C# 4.0


This new feature of c# 4.0 allows uses to define optional parameter for the methods. With this new feature user can call method by passing only necessary parameters and rest of the unnecessary parameters can be omitted. But the unnecessary parameters should be declared as optional as shown below i.e. by providing default value:

//by default calculates the square of x
static double CalculatePower(double x, double n=2)
{
    return Math.Pow(x,n);
}

W
hen you write this method in vs2005/2008 you will get following error:

1.gif

In the above CalculatePower method the default value for parameter n Is 2. When user calls this method only with one parameter then the n will hold the default value i.e. 2. Thus by default above method calculates the square of x other wise n to the power of x.
Following is the sample main program which calls this method:

double
x = 2;
double n = 3;
double result=  CalculatePower(x);// calculates the square of x
Console.WriteLine("Result is :{0}", result);
result = CalculatePower(x,n); // calculates the n to the power of x
Console.WriteLine("Result is :{0}", result);
Next Recommended Reading C# 4.0 New Features