[Mono-list] Operator overloading

David Henderson dnadavewa at yahoo.com
Sat Jan 8 00:17:00 EST 2011

Ah, Got it!  Thanks!!

Would have been nice if I could have found some documentation leading me to that 
solution.  Is there a good site or text I should be using?  The ones I have 
evidently stink...

----- Original Message ----
From: Jonathan Pryor <jonpryor at vt.edu>
To: David Henderson <dnadavewa at yahoo.com>
Cc: Mono List <mono-list at lists.ximian.com>
Sent: Fri, January 7, 2011 7:35:05 PM
Subject: Re: [Mono-list] Operator overloading

On Jan 7, 2011, at 8:35 PM, David Henderson wrote:
> OK.  I have been trying to no avail to overload the > and < operators on a 
> struct I wrote.  This is extremely easy in C++, but seems to not work in C#.

You have properly overloaded operator< and operator>; they are not the problem.

> Here is the error I see at runtime:
> Unhandled Exception: System.InvalidOperationException: The comparer threw an 
> exception. ---> System.ArgumentException: does not implement right interface

Admittedly the exception message doesn't tell you what interface is missing, but 
it does mention that you're not implementing an interface.

The problem is that the operators you're providing are static members, while 
interfaces (which the exception mentions) can only be implemented in via 
instance members.

In short: this isn't C++, and providing operator< does NOT automatically provide 
comparison for your type.

Instead, you need to implement either the System.IComparable or the 
System.IComparable<T> interfaces on your type, which will allow use of 
Comparer<T>.Default (which is what System.Array.qsort() is using):

    struct lodData : IComparable<lodData> {
        public int CompareTo (lodData other)
            if (getLOD() == other.getLOD())
                return 0;
            if (getLOD() < other.getLOD())
                return -1;
            return 1;
        // ...

- Jon


More information about the Mono-list mailing list