Does a subclass inherit the base's interface as well?

S

Stu

I have a base class which implements the IComparable interface. I
then have a subclass of that which I assumed would inherit the
IComparable implementation in the base class, but it doesn't seem to
have done so since I can't call the CompareTo method on the subclass.
Note that I'm using IComparable<T> with the type being the type of my
base class, but I would still expect that to work. Am I incorrect?
 
S

Stu

I have a base class which implements the IComparable interface.  I
then have a subclass of that which I assumed would inherit the
IComparable implementation in the base class, but it doesn't seem to
have done so since I can't call the CompareTo method on the subclass.
Note that I'm using IComparable<T> with the type being the type of my
base class, but I would still expect that to work.  Am I incorrect?

Actually never mind, as expected it was a dumb error on my part. I
had declared the CompareTo method in my base class Effort as:
public int IComparable<Effort>.CompareTo(Effort other)
since I had seen that syntax in an example. Simply declaring it as
this fixed the problem:
public int CompareTo(Effort other)
 
P

Peter Duniho

Stu said:
I have a base class which implements the IComparable interface. I
then have a subclass of that which I assumed would inherit the
IComparable implementation in the base class, but it doesn't seem to
have done so since I can't call the CompareTo method on the subclass.
Note that I'm using IComparable<T> with the type being the type of my
base class, but I would still expect that to work. Am I incorrect?

A class that implements IComparable does not automatically implement
IComparable<T>.

Since you didn't post a concise-but-complete code example, there's no
way to know for sure. But based on your description, it sounds as
though everything is working exactly as expected. Either use
IComparable instead of IComparable<T>, or implement IComparable<T>.

In addition, note that inheriting comparison logic is somewhat fragile.
You need to be very careful when doing so, to ensure that things
continue to work in the expected and desirable way. In particular, the
subclass typically adds some state to the object that probably ought to
be considered in a comparison, which means you need to override the
comparison implementation rather than just using the base implementation.

Typically, a much better approach is to use explicit Comparision<T> or
IComparer<T> implementations, rather than trying to building
comparability into the classes themselves.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top