1. Home
  2. Computing & Technology
  3. Visual Basic

Operator Overloading

The Completed Overloaded Operators

By Dan Mabbutt, About.com

Sep 9 2007

To create the full class, just pop this into the If clause of the program. The Else clause just calls the processing and reverses the result.

Public Class Particle
Public Strangeness As Integer
Public Charm As Integer
Public Topness As Integer

Public Shared Operator >( _
   ByVal value1 As Particle, _
   ByVal value2 As Particle) _
   As Boolean
   If value1.Strangeness > value2.Strangeness _
      And value1.Charm / value2.Charm < 0.5 _
      And value1.Topness * value2.Topness > 20 _
   Then
      Return True
   Else
      Return False
   End If
End Operator
Public Shared Operator <( _
   ByVal value1 As Particle, _
   ByVal value2 As Particle) _
   As Boolean
   If value1 > value2 Then
      Return False
   Else
      Return True
   End If
End Operator
End Class

Using our new overloaded relationship is simple. Just fill in the values of the values in the Particles and ... well ... use it.

Public Class Form1
   Dim Particle1 As New Particle
   Dim Particle2 As New Particle
   Private Sub Button1_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button1.Click

      Particle1.Strangeness = 20
      Particle2.Strangeness = 10
      Particle1.Charm = 20
      Particle2.Charm = 100
      Particle1.Topness = 3
      Particle2.Topness = 10
' This uses the overloaded relation
      If Particle1 > Particle2 Then
         MsgBox("Particle 1 is greater than Particle 2")
      Else
         MsgBox("Particle 2 wins instead")
      End If
   End Sub
End Class

What about operator shortcuts? What if you use the new feature of VB.NET that lets you combine an operator like "+" with "="? Find out on the next page!

Explore Visual Basic

More from About.com

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Using VB.NET
  5. Operator Overloading

©2008 About.com, a part of The New York Times Company.

All rights reserved.