Interfaces & Inheritance

E

Eric

Let's say I have a base class that implements IComparable<baseClass>. Really
it could be any interface but I'm picking that one for the sake of
discussion. In this class, equality and comparisons are based on a string
representation of it's attributes - a subclass may add an attribute but
still uses a string representation for equality and comparison.

So if I can avoid it, I'd like to have all my tests and code associated with
the base class. Must I have the subclass also implement
IComparable<subClass> and then make wrapper calls to the base class? Would I
be better off using composition than inheritance?

I may be working way too hard to save some work, but I'd like to explore the
idea.

Thanks,
Eric
 
M

Marc Gravell

Must I have the subclass also implement
IComparable<subClass> and then make wrapper calls to the base class? Would I
be better off using composition than inheritance?

Well, as long as baseClass also implements IComparable, then it mainly
depends on how you later use it. For example, if you have a
List<subClass> and call Sort(), it will use Comparer<T>.Default; if
subClass doesn't implement IComparable<subClass>, then this will fall
back to using the non-generic IComparable interface, so as long as
baseClass : IComparable, things should still work. Since we are
talking about a class (not a struct) there is no boxing overhead here
- just a little casting overhead.

Of course, if you only use comparers based on baseClass (i.e.
List<baseClass>.Sort()) then it will use your IComparable<baseClass>,
and no casting is required. There is nothing to stop your subClass
implementing IComparable<subClass>, but it gets confusing - and you'd
still want the comparisons to work out the same regardless of whether
IComparable, IComparable<baseClass> or IComparable<subClass> was used
- so perhaps just draw the line at IComparable and
IComparable<baseClass> (both calling the same actual method to do the
work).

Marc
 

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