Private Interface Implementation in Inherited Types

Problem
You want to know how to implement private interface members in inheritable types.

Solution
Ensure that derived types can access and override nonpublic members in nonsealed classes.

Comments
In order to implement this scenario in C#, you need to define a protected virtual method and call it from the interface method.

Example

public class Account : IComparable {
    // Implement IComparable privately.
    int IComparable.CompareTo(object obj) {
        // Delegate to a protected virtual method.
        return CompareTo(obj);
    }

    // Protected method that derived types can override.
    protected virtual int CompareTo(object obj) {
        // Do the comparison 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