Summary: in this tutorial, you’ll learn how to use the C# default parameters to simplify the function call.
Introduction to the C# default parameters
When defining a function with parameters, you can specify the default arguments like this:
<modifiers> <return-type> functionName(parameter1,parameter2=argument2,...)Code language: C# (cs)C# requires that the parameters with default arguments appear after other parameters.
The following example defines a function calculateTax() that calculates the net price based on the selling price and sales tax:
double calculatePrice(double sellingPrice, double salesTax=0.08)
{
return sellingPrice * (1 + salesTax);
}Code language: C# (cs)In this example, the salesTax parameter has a default value of 0.08.
When calling the function, if you don’t specify the argument for the parameter with default arguments, the function will take the default argument instead.
For example:
double calculatePrice(double sellingPrice, double salesTax=0.08)
{
return sellingPrice * (1 + salesTax);
}
var netPrice = calculatePrice(100);
Console.WriteLine($"The net price is {netPrice:0.##}");Code language: C# (cs)Output:
108Code language: C# (cs)In this example, we only pass the selling price to the calculatePrice() function. Therefore, the calculatePrice() function will use 0.08 for the salesTax parameter. As a result, the net price is 108.
If you pass the salesTax argument, the function will use that value instead of the default argument. For example:
double calculatePrice(double sellingPrice, double salesTax=0.08)
{
return sellingPrice * (1 + salesTax);
}
var netPrice = calculatePrice(100,0.1);
Console.WriteLine($"The net price is {netPrice:0.##}");Code language: C# (cs)Output:
110Code language: C# (cs)In this example, we pass the salesTax as 0.1 to the calculatePrice() function. Hence, the function uses 0.1 instead of 0.08 for the salesTax parameter.
Summary
- Use function default parameters to simplify the function call
- Place the parameters with default values after other parameters.