471,310 Members | 1,390 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,310 software developers and data experts.

Interfaces & Inheritance

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<subClassand 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
Jun 27 '08 #1
1 1167
Must I have the subclass also implement
IComparable<subClassand 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<subClassand 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<baseClassor IComparable<subClasswas used
- so perhaps just draw the line at IComparable and
IComparable<baseClass(both calling the same actual method to do the
work).

Marc
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Shawn Casey | last post: by
21 posts views Thread by Franco Gustavo | last post: by
30 posts views Thread by Frank Rizzo | last post: by
22 posts views Thread by RSH | last post: by
23 posts views Thread by Dave Rahardja | last post: by
23 posts views Thread by A.Gallus | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.