C# Optional parameters

Description

Methods, constructors, and indexers can declare optional parameters.

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

  • Optional parameters may be omitted when calling the method:
  • Optional parameters cannot be marked with ref or out.

Example

Example for Optional parameters


using System;/* ww w .  ja va2 s.c  o  m*/

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

        output();
        output(10);
    }
}

The output:

Note

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

The exception is with params arguments, which still always come last.

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


void Foo (int x = 0, int y = 0) { 
   Console.WriteLine (x + ", " + y); 
} /* ww w .  ja  v a 2s  .  co m*/

void Test() 
{ 
   Foo(1);    // 1, 0 
} 

To do the converse (pass a default value to x and an explicit value to y), you must combine optional parameters with named arguments.

Optional parameters cannot be marked with ref or out. And optional parameters must be declared before any another parameters. When calling a method with optional parameters we provide the optional parameters first.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor