When to use optional parameters above overloading and vice versa?

3

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 overridden by overload method signature

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

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

    
asked by anonymous 04.10.2017 / 21:48

2 answers

4

Technical limitations

Exposing methods with optional parameters like APIs for other languages that do not support this functionality causes problems, in this case overloading methods is recommended.

Reflection operations also display incompatibility with optional parameters.

Functionality

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

Taking the technical limitations and functionality, the next points are subjective , that is, preference, liking and alignment with your team / team of employee code:

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 reducing the amount of code. Consequently, there will be less documentation with% of%.

Optional parameters = More concise Intellisense

With optional parameters, VS Intellisense displays the method on one line only with the optional parameters:

Withmethodoverload,youhavetonavigatethrougheachmethodtofindwhatyouwant:

Reference

    
04.10.2017 / 21:55
1

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

In a function that has other overloads, the use of the parameters are explained in its call, giving a basic notion of what will be done in its internal logic. This makes it possible for those who use this function to decide what would be the best performance of a task.

    
04.10.2017 / 22:18