Optional parameters - CSharp Custom Type

CSharp examples for Custom Type:Method Parameter

Introduction

A parameter is optional if it specifies a default value in its declaration.

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.

void Foo (int x = 23) { Console.WriteLine (x); }

Optional parameters may be omitted when calling the method:

Foo();     // 23

The preceding call to Foo is semantically identical to:

Foo (23);

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 Code

using System;/*from  ww  w.  ja  v a 2s. co m*/
class Test
{
   static void Foo (int x = 0, int y = 0) { Console.WriteLine (x + ", " + y); }
   static void Main(){
      Foo(1);    // 1, 0
   }
}

Result


Related Tutorials