Thursday 19 July 2012

OPTIONAL PARAMETERS


An optional parameter has a default value. A method with an optional parameter can be called with only some of its parameters specified. Using this feature in new versions of the C# language, we add default values for formal parameters.

Example

In this example, we introduce a method named "Method" that has two parameters. Each of the parameters is optional. To specify an optional parameter, assign the formal parameter in the method parameter list to an appropriate value.

Here, we set the formal parameter 'value' to 1, and the formal parameter 'name' to "Perl". Whenever Method is called without a parameter specified, its default value is used instead in the method body.

Program that uses optional parameters [C# 4.0]

using System;
class Program
{
    static void Main()
    {
          // Omit the optional parameters.
          Method();

          // Omit second optional parameter only.
          Method(4);

          // You can't omit the first but keep the second.
          // Method("Dot");

          // Classic calling syntax.
          Method(4, "Dot");

          // Specify one named parameter.
          Method(name: "Sam");

          // Specify both named parameters.
          Method(value: 5, name: "Allen");
    }

    static void Method(int value = 1, string name = "Perl")
    {
          Console.WriteLine("value = {0}, name = {1}", value, name);
    }
}

Output

value = 1, name = Perl
value = 4, name = Perl
value = 4, name = Dot
value = 1, name = Sam
value = 5, name = Allen

This example shows that you can call Method() with no parameters at all; you can call it with only an integer parameter; you can use the regular calling syntax from previous versions of the C# language; and you can use the named parameter feature to specify one or both parameters.

No comments:

Post a Comment