7

I'm mucking about, making a generic class, and all this time I thought using types that implemented IComparable enabled using the comparison operators.

I know .CompareTo() can perform functionally the same operations, but I have a nagging feeling that there must be an interface that implements the comparison operators.

0

2 Answers 2

6

Rather than by implementing an interface, this is accomplished through operator overloading. So, to overload the greater-than and less-than comparison operators, for instance, you could do something like this:

Public Class MyNumber
    Public Value As Integer

    Public Overloads Shared Operator >(ByVal x As MyNumber, ByVal y As MyNumber) As Boolean
        Return (x.Value > y.Value)
    End Operator

    Public Overloads Shared Operator <(ByVal x As MyNumber, ByVal y As MyNumber) As Boolean
        Return (x.Value < y.Value)
    End Operator
End Class

Since operator overloads are defined as Shared, they cannot be declared by an interface. Interfaces in VB.NET can only declare instance-members. They cannot declare shared members.

3
  • 2
    That's a good tip, but overloading the operators isn't a solution since I'm working with generics. I didn't realize static / Shared functions can't be part of interfaces though, good to know.
    – j.i.h.
    Jan 7, 2013 at 19:10
  • 1
    @j.i.h. If that's the case, that's what the interfaces such as IComparable are for. That's why they exist. You just have go through the interface to perform the comparison operation, unfortunately. Jan 7, 2013 at 19:15
  • 1
    Unfortunately, you can't constrain generic types based on which operators they support. Jan 7, 2013 at 19:25
5

No. Operators cannot be specified via an interface.

Interfaces define the properties, methods, and events [but not operators] that classes can implement.

The closest interface, as noted, is IComparable.

Some languages have more sugar mapping (e.g Scala) but not VB.NET or C#.

1
  • This deficit is particularly frustrating as the IComparable.CompareTo method doesn't have the same behaviour as the <, > and == operators for some edge cases, such as comparisons involving Double.NaN.
    – andypea
    Apr 15, 2021 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.