tags:

views:

84

answers:

2

This might be a trivial question, but I didn't find any information about this: is it "harmful" or considered bad practice to make a type T implement IComparable<S> (T and S being two different types)?

Example:

class Foo : IComparable<int>
{
    public int CompareTo(int other)
    {
        if (other < i) return -1;
        if (other > i) return 1;

        return 0;
    }

    private int i;
}

Should this kind of code be avoided, and if yes, why?

+5  A: 

I would at least consider it "odd" - in particular at that point the comparison isn't going to be symmetric, which is usually part of normal comparison contracts.

If there's a particular situation where it's simpler than any other implementation of what you want to do, that would be okay - but I can't say I've ever come across such a situation. Comparisons like this are almost always used for sorting a homogeneous collection or something similar.

Did you have a particular situation in mind, or is it just a "for interest" question?

Jon Skeet
I was just curious :-)!
Luc Touraille
+1  A: 

It is fancy to implement such things. But it is not a good practice.

Imagine you see some code like this:

Foo x = new Foo();

if( x.compareTo(15) > 0)
{
  //blah blah
}

You will say "oh my god! how to compare 15 to x?"? This will make code less readable..

It is better to add compare as function like this: public int IsMoreThanPrivateI(int x);

Yousf
That's overloading an operator, which isn't quite the same thing really.
Jon Skeet
you are right jon, I edited the answer.
Yousf