This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Forced Override of Virtual Methods

Some scenarios require that virtual methods must be overridden in subclasses of a given type, an example being a requirement to override GetHashCode and Equals in data objects. This example describes how to enforce such overriding.

Virtual and Abstract Methods

When you create a virtual method in a class, you provide that method with a body that executes some functionality and, optionally, returns a value. By making the method virtual, you allow it to be overridden by subclasses of the type. The subclasses can provide an alternative method with different functionality. However, if you create a subclass and do not override the virtual method, the base class's version is automatically inherited. This is somewhat different to an abstract method, which can only be added to an abstract class. Abstract methods provide no functionality and must be overridden in any subclasses.

There are situations where you may wish to ensure that subclasses of a given type override a virtual method, rather than using the code that the method defines in the base class. This might be to enforce overriding of virtual methods in your own custom classes, or methods in standard .NET framework types.

One common example of this technique is to force overriding of the ToString, Equals and GetHashCode methods, which are defined in System.Object. You might do this, along with overloading the == operator, to make sure that the Equals method does not use simple reference equality for your application's data objects. Doing so correctly requires that both Equals and GetHashCode are overridden. You might override ToString to include important information about a data object for use during logging operations.

To ensure that these three methods are overridden by subclasses of an abstract DataObject class, you must override them in that type. Additionally, the new methods must be marked as abstract. This is shown in the sample class below:

public abstract class DataObject
    public abstract override string ToString();
    public abstract override bool Equals(object obj);
    public abstract override int GetHashCode();

To demonstrate what happens when derived types do not implement the now abstract methods, we can use the following class. The empty type does not include any of the three expected members.

public class Employee : DataObject

Building the project now generates an error for each missing method. The errors describe the problem and are similar to the following:

'ConsoleApplication1.Employee' does not implement inherited abstract member
30 August 2013