Overloaded Virtual Methods

Problem
You want to know what to do when you have an overloaded method and want to allow developers to override it in derived types.

Solution
Make the most complete version of the method virtual and have all other versions call it.

Comments
This practice simplifies the process of redefining the method in derived classes because inheritors only have to override one method. There is an alternative approach. You can make overloaded methods sealed–not marked virtual–and have them call a protected overridable method. The naming convention for the called method is MethodNameCore. This approach requires a little more code, but it expresses the relationship between public sealed and protected overridable methods more clearly. This technique is frequently used in the .NET Framework, and a variation of it is often applied to properties.

// The original approach.
public void DoWork(int argOne) {
    // Call the other overload.
    DoWork(argOne, "Years");
}

// The only method that needs to be overridden in a derived class.
public virtual void DoWork(int argOne, string argTwo) {
    // Do the work here.
    ...
}

// The alternative approach.
public void DoWork(int argOne) {
    // Call the protected method.
    DoWorkCore(argOne, "Years");
}

public void DoWork(int argOne, string argTwo) {
    // Call the protected method.
    DoWorkCore(argOne, argTwo);
}

// The only method that needs to be overridden in a derived class.
protected virtual void DoWorkCore(int argOne, string argTwo) {
    // Do the work here.
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s