Brad
Brad

Reputation: 163282

Allow math to occur on instances of my class

Is there some interface I can implement to allow basic comparisons and math to happen as it would an integer?

For example, let's say I have the following class:

Public Class Something
    Public SomeBigNumber as UInt64
End Class

I would like to do something like this:

Dim SomethingA, SomethingB, SomethingC as New Something

....

If (SomethingA-SomethingB) > SomethingC Then
    'Do stuff
End If

I was hoping to be able to implement some interface (if that is even the right term for it) that would return the UInt64 contained in the class for comparison and math, if possible.

Thoughts? Thanks in advance!

Upvotes: 1

Views: 67

Answers (1)

Cody Gray
Cody Gray

Reputation: 244782

What you are seeking to do is called "operator overloading", which allows you to define comparison and mathematical operators for complex types (like your class Something).

For example, you can overload the addition and subtraction operators from within your Something class like this:

Public Shared Operator +(ByVal val1 As Something, ByVal val2 As Something) As Something
    ''#(calculate the sum of the two specified values)
    Return New Something(val1.SomeBigNumber + val2.SomeBigNumber)
End Operator

Public Shared Operator -(ByVal val1 As Something, ByVal val2 As Something) As Something
    ''#(calculate the difference of the two specified values)
    Return New Something(val1.SomeBigNumber - val2.SomeBigNumber)
End Operator

And then you can write code like:

Dim newValue As Something = something1 + something2


You can also overload the comparison operators (greater than, less than, equal to, and everything in between) in almost exactly the same way:

Public Shared Operator >(ByVal val1 As Something, ByVal val2 As Something) As Boolean
    ''#(return True if the first value is larger, False otherwise)
    Return (val1.SomeBigNumber > val2.SomeBigNumber)
End Operator

Public Shared Operator <(ByVal val1 As Something, ByVal val2 As Something) As Boolean
    ''#(return True if the first value is smaller, False otherwise)
    Return (val1.SomeBigNumber < val2.SomeBigNumber)
End Operator

Allowing you to write code like:

If something1 > something2 Then
    MesssageBox.Show("The first value is larger.")
Else
    MessageBox.Show("The second value is larger.")
End If

Note, however, that some of these operators must be overloaded in pairs. Specifically:

  • = and <>
  • > and <
  • >= and <=
  • IsTrue and IsFalse

Upvotes: 4

Related Questions