Monday, November 15, 2010

C# 4.0 new feature (2) --Optional Parameters and Named Parameters

For example:

class Program
{
static void Main(string[] args)
{
Console.WriteLine(Cal(5,b:20,c:30));

Console.WriteLine(Cal(5,20, d:false));
}

private static int Cal(int a, int b = 0, int c = 50, bool d = true)
{
int i = a + b - c;
int j = a - b + c;

if (d == true)
return i;
else
return j;
}
}

result:
-5 //true, 5+20-30
35 //false,5-20+50

Sometimes we need to consider matching rule:
The method is be called will be the fewest parameters and also the type should be matched.

forexample:

class Program
{
static void Main(string[] args)
{
Console.WriteLine(Add(5));

Console.WriteLine(Add(5,10));
}

private static int Add(int i)
{
return i+2;
}
private static int Add(int i,int j)
{
return i+j;
}
private static double Add(int i,double j)
{
return i+j+2.0;
}
result:
7
10

No comments: