How to: Define an Operator (Visual Basic)

If you have defined a class or structure, you can define the behavior of a standard operator (such as *, <>, or And) when one or both of the operands is of the type of your class or structure.

Define the standard operator as an operator procedure within the class or structure. All operator procedures must be Public Shared.

Defining an operator on a class or structure is also called overloading the operator.


The following example defines the + operator for a structure called height. The structure uses heights measured in feet and inches. One inch is 2.54 centimeters, and one foot is 12 inches. To ensure normalized values (inches < 12.0), the constructor performs modulo 12 arithmetic. The + operator uses the constructor to generate normalized values.

Public Shadows Structure height
    ' Need Shadows because System.Windows.Forms.Form also defines property Height. 
    Private feet As Integer 
    Private inches As Double 
    Public Sub New(ByVal f As Integer, ByVal i As Double)
        Me.feet = f + (CInt(i) \ 12)
        Me.inches = i Mod 12.0
    End Sub 
    Public Overloads Function ToString() As String 
        Return Me.feet & "' " & Me.inches & """" 
    End Function 
    Public Shared Operator +(ByVal h1 As height, 
                             ByVal h2 As height) As height
        Return New height(h1.feet + h2.feet, h1.inches + h2.inches)
    End Operator 
End Structure

You can test the structure height with the following code.

Public Sub consumeHeight()
    Dim p1 As New height(3, 10)
    Dim p2 As New height(4, 8)
    Dim p3 As height = p1 + p2
    Dim s As String = p1.ToString() & " + " & p2.ToString() &
          " = " & p3.ToString() & " (= 8' 6"" ?)" 
    Dim p4 As New height(2, 14)
    s &= vbCrLf & "2' 14"" = " & p4.ToString() & " (= 3' 2"" ?)" 
    Dim p5 As New height(4, 24)
    s &= vbCrLf & "4' 24"" = " & p5.ToString() & " (= 6' 0"" ?)"
End Sub

For more information and examples, see Operator Overloading in Visual Basic 2005.

See Also


How to: Define a Conversion Operator (Visual Basic)

How to: Call an Operator Procedure (Visual Basic)

How to: Use a Class that Defines Operators (Visual Basic)

How to: Declare a Structure (Visual Basic)


Operator Statement

Structure Statement

Mod Operator (Visual Basic)


Operator Procedures (Visual Basic)