Optional parameters
In this chapter you will learn:
Create optional parameters
Methods, constructors and indexers can have optional parameters. An optional parameter is declared with default value.
using System;/*from j av a 2s .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:
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.
using System;/*ja v a 2 s .com*/
class Program
{
static void output(int i = 5, int j = 6)
{
Console.WriteLine("i=" + i);
Console.WriteLine("j=" + j);
}
static void Main(string[] args)
{
output();
output(10);
output(10, 20);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to define named parameters for methods
- Method call and named parameters
- Mix the positional parameter and named parameter
Home » C# Tutorial » Class