C# Optional parameters
In this chapter you will learn:
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:
- What is method overloading
- How to create overloaded methods
- Note for Pass-by-value versus pass-by-reference
- Example for method overload
- What are the easy errors in method overloading
- return type is not part of the signature
- ref and out modifiers and method overloading
- ref and out cannot coexist
- How is the type conversion affecting the method overloading