[Mono-list] Operator overloading

Jonathan Pryor jonpryor at vt.edu
Fri Jan 7 22:35:05 EST 2011

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