C# Optional parameters

In this chapter you will learn:

  1. What is C# Optional parameters
  2. Example for Optional parameters
  3. Note for 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;//from ww  w .  j  a  va 2 s .com

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); 
} //  w  w  w . j ava 2  s.c o 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.

Next chapter...

What you will learn in the next chapter:

  1. What is method overloading
  2. How to create overloaded methods
  3. Note for Pass-by-value versus pass-by-reference
  4. Example for method overload
  5. What are the easy errors in method overloading
  6. return type is not part of the signature
  7. ref and out modifiers and method overloading
  8. ref and out cannot coexist
  9. How is the type conversion affecting the method overloading
Home »
  C# Tutorial »
    C# Types »
      C# Method
C# class method
C# method parameters
C# ref parameter
C# out parameter
C# named parameters
C# params parameters
C# Optional parameters
C# method overloading
Recursive methods
C# Return Statement
static method
C# Main Function
C# Extension Methods