1553.md
February 3, 2022 ยท View on GitHub
The only valid reason for using C# 4.0's optional parameters is to replace the example from rule [{{ site.default_rule_prefix }}1551](#{{ site.default_rule_prefix }}1551) with a single method like:
public virtual int IndexOf(string phrase, int startIndex = 0, int count = -1)
{
int length = count == -1 ? someText.Length - startIndex : count;
return someText.IndexOf(phrase, startIndex, length);
}
Since strings, lists and collections should never be null according to rule [{{ site.default_rule_prefix }}1135](/member-design-guidelines#{{ site.default_rule_prefix }}1135), if you have an optional parameter of these types with default value null then you must use overloaded methods instead.
Strings, unlike other reference types, can have non-null default values. So an optional string parameter may be used to replace overloads with the condition of having a non-null default value.
Regardless of optional parameters' types, following caveats always apply:
-
The default values of the optional parameters are stored at the caller side. As such, changing the default argument without recompiling the calling code will not apply the new default value. Unless your method is private or internal, this aspect should be carefully considered before choosing optional parameters over method overloads.
-
If optional parameters cause the method to follow and/or exit from alternative paths, overloaded methods are probably a better fit for your case.