When using optional parameters above overloading and vice versa?

Asked

Viewed 624 times

4

An optional parameter in C# is declared as follows (see parameter y):

public void DoFoo(String x, String y = "") { ... }

In many cases, this Feature can be replaced by Overload signature of the method

public void DoFoo(String x) { ... }
public void DoFoo(String x, String y) { ... }

When the best option would be to use overloading above an optional parameter and vice versa?

2 answers

5


Technical limitations

Exposing methods with optional parameters such as Apis to other languages that do not support this feature generates problems, in this case method overload is recommended.

Operations with Reflection also present incompatibility with optional parameters.

Functionality

Does your method do the same thing regardless of parameters? If yes, use optional parameters, if not using method overload. Different functionalities should be in different methods.

Aside from the technical limitations and functionality, the next points are subjective, i.e., it is a matter of preference, taste and alignment with your team/team in relation to the code style employed:

Optional parameters = Less code

Method overload:

public void Method(string str1)
{
   // ...
}

public void Method(string str1, string str2)
{
   // ...
}

Optional parameters:

public void Method(string str1, string str2 = null)
{
   // ...
}

In the example above, only one method is required, significantly decreasing the amount of code. Consequently, there will be less documentation XML.

Optional parameters = more concise intellisense

With optional parameters, VS Intellisense displays the method in a single line with optional parameters:

OP

With method overload, you have to navigate through each method to find what you want:

OL1 OL2 OL3

Reference

1

The use of optional parameters delegate to function logic how the internal operations will be made, not letting the function call decide what will be the behavior and use of these parameters.

In a function that has other overloads, the use of parameters are made explicit in its call, giving a basic notion of what will be done in its internal logic. This enables those who use this function to decide which would be the best accomplishment of a given task.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.