TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C# Coding Standard
Search

Rule:  7@303Checked automatically with code checker

Synopsis:If you must provide the ability to override a method, make only the most complete overload virtual and define the other operations in terms of it
Language:C#
Severity Level:6
Category:Object oriented


Description:

Using the pattern illustrated below requires a derived class to only override the virtual method. Since all the other methods are implemented by calling the most complete overload, they will automatically use the new implementation provided by the derived class.

public class MultipleOverrideDemo
{
	private string someText;

	public MultipleOverrideDemo(string s)
	{
		this.someText = s;
	}
	
	public int IndexOf(string s)
	{
		return IndexOf(s, 0);
	}

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

	// Use virtual for this one.
	public virtual int IndexOf(string s, int startIndex, int count)
	{
		return someText.IndexOf(s, startIndex, count);
	}
}

An even better approach, not required by this coding standard, is to refrain from making virtual methods public, but to give them protected accessibility, changing the sample above into:

public class MultipleOverrideDemo
{
	// same as above ...
	public int IndexOf(string s, int startIndex, int count)
	{
		return InternalIndexOf(s, startIndex, count);
	}

	// Use virtual for this one.
	protected virtual int InternalIndexOf(string s, int startIndex, int count)
	{
		return someText.IndexOf(s, startIndex, count);
	}
}