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:
With method overload, you have to navigate through each method to find what you want:
Reference