CSharp - Method Optional Parameters

Introduction

Methods, constructors, and indexers can have optional parameters.

An optional parameter has a default value in its declaration:

void Test (int x = 1) { 
   Console.WriteLine (x); 
}

Optional parameters may be omitted when calling the method:

Test();  // 1

The default argument of 1 is passed to the optional parameter x.

The preceding call to Test is semantically identical to:

Test (1);

The compiler simply substitutes the default value of an optional parameter wherever it is used.

The default value of an optional parameter must be specified by a constant expression, or a parameterless constructor of a value type.

Optional parameters cannot be marked with ref or out.

Mandatory parameters must occur before optional parameters in both the method declaration and the method call.

In the following example, the explicit value of 1 is passed to x, and the default value of 0 is passed to y:

Demo

using System;
class MainClass/*from   w  ww  . j  ava  2s  .c  om*/
{
    public static void Main(string[] args)
    {
        Test(1);    // 1, 0
    }
    static void Test(int x = 0, int y = 0)
    {
        Console.WriteLine(x + ", " + y);
    }
}

Result