1551.md

February 3, 2022 ยท View on GitHub

This guideline only applies to overloads that are intended to provide optional arguments. Consider, for example, the following code snippet:

public class MyString
{
	private string someText;

	public int IndexOf(string phrase)
	{
		return IndexOf(phrase, 0);
	}

	public int IndexOf(string phrase, int startIndex)
	{
		return IndexOf(phrase, startIndex, someText.Length - startIndex);
	}

	public virtual int IndexOf(string phrase, int startIndex, int count)
	{
		return someText.IndexOf(phrase, startIndex, count);
	}
}

The class MyString provides three overloads for the IndexOf method, but two of them simply call the one with one more parameter. Notice that the same rule applies to class constructors; implement the most complete overload and call that one from the other overloads using the this() operator. Also notice that the parameters with the same name should appear in the same position in all overloads.

Important: If you also want to allow derived classes to override these methods, define the most complete overload as a non-private virtual method that is called by all overloads.