Interfaces & Inheritance

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Eric

    Interfaces & Inheritance

    Let's say I have a base class that implements IComparable<bas eClass>. 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<sub Classand 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


  • Marc Gravell

    #2
    Re: Interfaces &amp; Inheritance

    Must I have the subclass also implement
    IComparable<sub Classand 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<subClassan d call Sort(), it will use Comparer<T>.Def ault; if
    subClass doesn't implement IComparable<sub Class>, 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<bas eClass>,
    and no casting is required. There is nothing to stop your subClass
    implementing IComparable<sub Class>, but it gets confusing - and you'd
    still want the comparisons to work out the same regardless of whether
    IComparable, IComparable<bas eClassor IComparable<sub Classwas used
    - so perhaps just draw the line at IComparable and
    IComparable<bas eClass(both calling the same actual method to do the
    work).

    Marc

    Comment

    Working...