Interfaces are one of the most common types in any C# application.
But did you know that you can make them more flexible by adding optional parameters to them?
Optional parameters in C# interfaces are a nice way to implement customized functionalities in your programs.
This article explains what optional parameters are, how to use them in interfaces, their different behaviors, and why and how you should use them in interfaces.
What are the optional parameters in C#?
First, some basics.
As you probably know, the C# method can have two types of parameters.
Required and optional parameters.
Required arguments are the parameters method caller must always specify values. On the other hand, optional parameters are parameters the method caller can be free to ignore. Depending on the functionality required, the method caller can include or omit them.
Not only in regular class methods, but also you can specify optional parameters in interfaces, indexers, and delegates.
Optional parameters were introduced in C# 4. Yeah, a long time ago.
When you define optional parameters, you need to define their default value. You can define the default value as:
- a constant expression,
- an expression that initializes a value type, e.g. new ValueType()
- or a default expression of a value type, e.g. default(ValueType)
The compiler will use the default value of the optional parameter if the caller does not specifically pass a value for it. Also, when declaring the parameters, named parameters should come first, or you must declare them at the end of the named parameter list.
Let’s look at the following example that illustrates the concept of optional parameters in C#.
public class OptionalParamsExample
{
public static void AddNumbers(int a, int b, int c = 10, int d = 20)
{
int total = a + b + c + d;
Console.WriteLine("Total: {0}", total);
}
public static void Main(string[] args)
{
AddNumbers(10, 10);
AddNumbers(10, 10, 30);
AddNumbers(10, 10, 30, 40);
}
}
In the above example program, the last two parameters of the AddNumbers
method are optional and contain default values.
Method calling AddNumbers(10, 10)
adds the default values, whereas the last two method callings replace the respective default values with the passed values.
How to use optional parameters in interfaces?
In C#, you can use optional parameters in interfaces by including a default value in the method declaration in the interface.
However, you do not have to declare optional parameters in the classes that implement them.
To better illustrate what I mean, let’s see two examples.
We have an IBonusCalculator
interface with the CalculateBonus
method. It has two parameters, and the second one is optional.
public interface IBonusCalculator
{
public double CalculateBonus(double salary, double percentage = 0.75);
}
public class BonusCalculator : IBonusCalculator
{
public double CalculateBonus(double salary, double percentage)
{
double bonus = ((salary * 12) * percentage) / 12;
return bonus;
}
}
public class OptionalParamsInInterfaceExample
{
public static void Main(string[] args)
{
IBonusCalculator ibcalculator = new BonusCalculator();
double bonus1 = ibcalculator.CalculateBonus(100000);
Console.WriteLine("Employee bonus with interface object {0} ", bonus1);
}
}
In this first example, we will initialize a new instance of the BonusCalculator, but the type of the initialized object is IBonusCalculator. You define the type on the left side of the initialization equation.
IBonusCalculator ibcalculator = new BonusCalculator();
In this example, the percentage parameter is optional and has a default value of 0.75.
Therefore, the implementing class OptionalParamsInInterfaceExample
has left out the value of the percentage parameter. In this case, the compiler will use the default value of 0.75 declared in the method signature. Therefore, the output of the program will be:
Employee bonus with interface object 75000
Now, let’s take a look at the second example.
This time, your program uses the implementing class object to call the interface method. In that case, you cannot leave out passing a value to the optional parameter as it is part of the required parameter list. Look at the following code snippet.
BonusCalculator bcalculator = new BonusCalculator();
double bonus2 = bcalculator.CalculateBonus(100000);
The program will not compile properly and will give the following error in this case.
There is no argument given that corresponds to the required formal parameter 'percentage' of 'BonusCalculator.CalculateBonus(double, double)'.
Therefore, you must specify a value for the percentage parameter.
Also, you can declare a value for the optional parameter in the implementing class. This option allows different classes implementing the same interface to have their own behavior.
public double CalculateBonus(double salary, double percentage = 0.50)
Now the output of the program will be:
Employee bonus with concrete class object 50000
However, using different values for optional parameters is not a good idea. It can be confusing to see what’s going on. Not to mention someone can spend hours and hours debugging when trying to find a bug in this code area.
But the conclusion is: the output differs based on how your object referenced has been cast.
If the object reference is an interface, it will use the interface default. If the reference is a class, the program uses the default value of the optional parameter defined in the class.
Should you use optional parameters in interfaces?
An interface is a contract that every class that implements it must follow. Optional arguments in interfaces are self-documenting and provide the flexibility to have different functionalities for the implementing classes.
Optional parameters can be valuable in interfaces because they allow developers to provide default values.
Essentially, they make the interface more flexible. On the other hand, classes that implement the interface have two choices:
- Include the optional parameter in the method definition.
- Omit the optional parameter from the method definition.
Including an optional parameter will probably feel more natural to most developers since the code will be more consistent.
Optional parameters make using the interface easier for method callers, as they do not have to specify a value for every parameter when calling them.
Also, optional parameters help avoid using the method overload in interfaces. For example, suppose there is a method with two parameters.
public void DoWork(int param1);
public void DoWork(int param1, int param2);
If you want to include method overloads that do and do not include parameter ‘param2’, you will have to implement two methods with the same name.
As a result, every implementing class will have to implement this extra method.
You can implement different behaviors with these two parameters using one method with optional parameters. You only must define one method. Therefore, optional parameters help reduce the lines of code and save developers valuable time.
Therefore, having optional parameters is convenient.
Nevertheless, it is crucial that you use optional parameters carefully in your code, as it is easier to introduce bugs if the default values are not suitable for all functionalities.
Conclusion
Optional parameters are the parameters you can either omit or choose to provide values.
In C#, you can declare optional parameters in interface method signatures but implementing classes do not have to provide a default value if you use interface references to call the method.
You use them for several reasons, such as to implement customizations and avoid method overload.