Saturday, May 23, 2009

Optional and Namded Prameters in C# 4.0

C# 4.0 is coming with a lot of new features. Covariance, Contra-variance, dynamic programming, optional parameters etc. Today I'll talk about my most favorite feature, which was available in C++, optional parameters.
We can use the optional parameters to reduce the number of method overloads. For example, upto C# 3.0 we had to write:

public class Complex
{
private double real, imag;
public Complex()
{
real = imag = 0.0;
}
public Complex(double r)
{
real = r;
imag = 0.0;
}
public Complex(double r, double img)
{
real = r;
imag = 0.0;
}
}

Now with C# 4.0, we can write above Complex class with a single constructor:
public class Complex
{
private double real, imag;
public Complex(double r = 0.0, double img = 0.0)
{
real = r;
imag = 0.0;
}
}

But, with C# 4.0, a new gift comes free. Named Parameters, not available in C++, make the order of parameters irrelevant. Consider this Main method:

public class Program
{
static void Main()
{
Complex c = new Complex(img:4.0); //Pass imaginary value, real is 0.0 by defalult
Complex c1 = new Complex(r:4.0); //Pass real value, imaginary is 0.0 by defalult
Complex c2 = new Complex(); //dont Pass any value, both are 0.0 by defalult
}
}

The parameters names are from the method definition.

No comments:

Post a Comment