Optional Parameters vs Method Overloading: 6 Key Differences


When you want to reuse a method or just its name: you have two options.

You can either use optional parameters or use method overloading.

Optional parameters allow you to call a method while omitting parameters that are not required. On the other hand, method overloading allows multiple methods to have the same name but vary on method parameters and return type.

There are several pros and cons to using these two methods.

This article explains what optional parameters and methods overload with a comparison between them. The article also provides some best practices you can follow if you intend to use them in your programs.

What are the optional parameters in C#?

Optional parameters are those parameters that are not mandatory to include in a method call. The caller is free to omit them based on the functionality they want from the method.

Optional parameters were introduced in C# 4. You can specify a parameter as optional by defining its 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)

If the method caller does not explicitly pass a value to it, the default value will be used for the method functionality.

In C#, you can specify optional parameters in classes, interfaces, indexers, and delegates. Also, optional parameters must be specified at the end of the parameter list.

The following simple program shows the use of optional parameters in methods.

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.

Required parameters and named parameters

To understand the optional parameters a little bit better, we also need to understand the alternative: required parameters.

Required parameters are mandatory for the method functionality. Therefore, the callers need to explicitly specify their values in the method call. By default, all method parameters are required if no optional parameters are specified.

There is also another term you can hear we someone mentions parameters, and that’s named parameters.

Named parameters are parameters you can refer to by their name so that you don’t have to remember the order of the parameters in a method.

For instance, look at the following method that prints the book details. It has three parameters:

  • bookId,
  • bookName,
  • and authorName.

You can call the method in the normal way specifying each parameter according to the order they are defined as follows.

 PrintBookDetails(100, “Harry Potter", J K Rowling");

You can call the same method by using named parameters as follows:

PrintBookDetails(bookId: 100, bookName: "Harry Potter", authorName: "J K Rowling");
PrintBookDetails(bookName: "Harry Potter,", authorName: "J K Rowling", bookId: 100);

In some cases, the named parameters can add clarity to the confusing method call. This is true, especially if you have more than 4-5 method parameters.

What is method overloading?

Method overloading is a technique in object-oriented programming where classes can have multiple methods with the same name but a different number of parameters, data types, and parameter order.

The return types of the overloaded can be changed, but they must have different parameters.

Therefore, method overloading can be achieved by:

  • By changing the number of parameters
  • By changing the parameter order,
  • By using different parameter data types.

The following example shows different ways the method PrintNumber has been overloaded.

void PrintNumber(int a) { ... }
void PrintNumber(int a, int b) { ... } 
void PrintNumber(int b, int a) { ... }
double PrintNumber(double a) { ... }
double PrintNumber(double a, float a) { ... }

Here is an example of method overloading by changing the number of parameters.

namespace MethodOverloadExample
{
    class Test
    {
        void PrintNumber(int a)
        {
            Console.WriteLine("Values: " + a);
        }

        void PrintNumber(int a, int b)
        {
            Console.WriteLine("Values: " + a + " and " + b);
        }

        static void Main(string[] args)
        {
            Test t = new Test();
            t.PrintNumber(50);
            t.PrintNumber(50, 60);
            Console.ReadLine();
        }
    }
}

The output:

Values: 50

Values: 50 and 60

The Test class has two methods with the same name but two parameters. The second method can provide its own implementation using an extra parameter. Therefore, method overloading can be used as an alternative to optional parameters.

Comparing optional parameters vs. method overloading

Let’s see when you can choose optional parameters and method overloading.

When to use optional parameters?

  1. To provide customized functionalities inside a single method.

You should use optional parameters to provide customized implementations in interfaces. The method callers can either omit or include them based on their requirements. They are a great way to implement simple and complicated functionalities simultaneously. If they have clear default values, users do not have to specify them every time they call your function manually.

  1. To reduce the number of overloaded methods and keep the programs simple and maintainable.

Method overloading is another way to provide customized implementation using the same method name. But you will have to declare multiple methods based on the parameters you require to include. For example, suppose there is a method with two parameters.

public void ExampleMethod(int param1);
public void ExampleMethod(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.

But, you can implement different behaviors with these two parameters using one method with optional parameters. In that case, you only need to define one method. Therefore, optional parameters help reduce the amount of code to maintain and save developer’s valuable time. Also, if you want to rename the method later, you must change it only in fewer places. Therefore, optional parameters are best if you want to reduce maintenance costs.

  1. When you want to allow the default values, keep them hidden from the method caller.

For example, suppose the following method contains several optional parameters with default values required to send an API request

SendApiRequest(“/test.com”);

The SendApiRequest method notices that various essential values have not been specified and use their defined default values (any query parameters, base URL, API method, etc.). The method is clean and hides unnecessary values from the user but has the flexibility to get different values for them.

When to use the method of overloading?

  1. To provide different functionalities using the same method name.

More than using optional parameters, using overloading, you can provide multiple functionalities in classes with the same method name based on different parameters, parameter data types, and return types.

It is best to avoid maintaining multiple method names in classes so that the callers will have to remember only a single method name. However, you need to know exactly how to declare the parameters and return types to call the overloaded method you want.

  1. If you want to provide a clear purpose for your methods.

It is best to make each method has one clear purpose and avoid programming clutter. When you use optional parameters, you may have to branch out the separate functionalities inside a single method.

The common scenarios that might occur with optional parameters are:

If you want to keep the method as simple as possible, you must find the right balance between method overloading and optional parameters. Also, if you must override a method with more than one optional parameter, it will be difficult to work with them.

  1. If you want to avoid possible versioning issues associated with optional parameters.

Suppose the current software version has a method with one optional parameter referred to by a client application. Then you decided to release its next version by adding another optional parameter. There can be run-time breakages if you do not recompile the client application.

But if you use method overloading instead, there will be no run-time breakages even if you can’t re-compile the application.

Therefore, if you want to avoid such breakages, it is best to use method overloading instead of optional parameters.

Comparison of optional parameters vs. method overloading: 6 key differences

Let’s see some differences between optional parameters and method overloading.

Optional ParametersMethod Overloading
A single method is used to provide different method behaviors with optional parameters.Multiple methods with the same method name but with a different number of parameters, parameter types, and parameter order are used to achieve different functionalities.
Reduce the number of code lines and the overhead of writing additional methods.It can increase the number of code lines.
Cannot change the behaviors of the method by parameter data types. The order can be changed for regular parameters using named arguments. Still, optional parameters need to be declared after the required parameters.Method caller can call the same method with different parameter data types. The order of parameters can vary.
A single method can branch out multiple functionalities, which can clutter the code.It helps clearly separate out the functionalities and keep the methods as clean as possible.
Improves the code readability by indicating the optional values.Improves the code readability by allowing methods to have a clear single purpose.
Improves the code maintainability as only a single method needs to be maintained.Improves the code maintainability by separating out specific functionalities.

Some best practices to follow

  1. Use method overloading if the method functionality gets bigger with many optional parameters. This can avoid complex code and keep it simple.
  2. Use optional parameters if your default values do not change often, or make sure the calling classes won’t be affected by frequently changing them.
  3. Use optional parameters to extend APIs so that the existing implementation won’t’ get affected.

Conclusion

Optional parameters and method overloading are two techniques programs can use to utilize the same method name for different behaviors. Optional parameters are best to reduce the number of method overloads and many other use cases described in this article.

Also, method overloading will be better in several instances than using optional parameters.

Therefore, the choice should be made wisely, considering your program requirements and the level of code readability and maintainability you want to achieve.

Recent Posts