Preliminary study on c#4.0: Optional and named parameters

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.