Optional parameters

Methods, constructors and indexers can have optional parameters.

An optional parameter is declared with default value.


using System;

class Program
{
    static void output(int i = 5)
    {
        Console.WriteLine("i=" + i);
    }
    static void Main(string[] args)
    {

        output();
        output(10);
    }
}

The output:


i=5
i=10

Optional parameters cannot be marked with ref or out.

Optional parameters must be declared before any another parameters.

When calling a method with optional parameters we provide the optional parameters first.


using System;

class Program
{
    static void output(int i = 5, int j = 6)
    {
        Console.WriteLine("i=" + i);
        Console.WriteLine("j=" + j);
    }


    static void Main(string[] args)
    {
        output();
        output(10);
        output(10, 20);
    }
}

The output:


i=5
j=6
i=10
j=6
i=10
j=20
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.