The Optional and named parameters features offer great convenience on some occasions, especially in office development where you can say goodbye to a bunch of System.Reflection.Missing. Here's a quick look at the optional and named parameters in c#4.0.
In the VS2010 CTP, the c#4.0 compiler debugging passes, the official version may have some changes.
1. Using the example
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.OptionalAndNamedParams(1);
t.OptionalAndNamedParams(2, "a");
t.OptionalAndNamedParams(3, c: "b", b: "a");
t.OptionalAndNamedParams(4, c: "http://g.cn");
}
}
class Test
{
// a为必选参数;b,c为可选参数
public void OptionalAndNamedParams(int a, string b = "", object c = "http://xianfen.net")
{
Console.WriteLine("a:{0}, b:{1}, c:{2}", a, b, c);
}
}
The results of the operation are:
Considerations in Use:
When a required parameter is mixed with an optional parameter in the same method, the declaration of the required argument should precede the optional argument.
The initial value of an optional parameter must be a constant that can be determined at compile time.
Optional parameters are not available with modifiers such as Ref,out.
If you explicitly specify the parameter name (paraname:value), the order of the parameters can be adjusted arbitrarily.