X

C# optional parameters

dotnet C#

C# 4.0 allows one to use named and optional parameters.

Example:


int Calculate(int x = 1, int y = 2)
{
   int someNumber = 0;
   //some algorithm to calculate
    return someNumber * y * x + 5 * 0.5;
}

One can call the method in multiple ways


int result = Calculate(1, 2);
int result = Calculate(5); //value for x only, y is default to 2
int result = Calculate(); //value for x is 1 and y is 2
int result = Calculate(x: 123, y: 987); //named argument
int result = Calculate(y: 345 x: 678); //named argument in reverse 
int result = Calculate(x: 123, 456); //compiler error not allowed position argument cannot follow name argument
int result = Calculate(1, y: 456); //name argument can follow position argument

Additional note, one cannot provide a gap in arguments.
Example:

int Calculate(int x, int y = 2, int z) //invalid
int Calculate(int x, int y = 1, int z= 5) //valid


int result = Calculate(1, , 3); //invalid
int result = Calculate(1, 8); //z takes the value of 5 as default
Categories: .NET C#
Taswar Bhatti:
Related Post