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

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

If you are using a class or structure that defines its own operators, you can access those operators from Visual Basic.

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

The following example accesses the SQL structure SqlString, which defines the conversion operators (CType Function) in both directions between a SQL string and a Visual Basic string. Use CType(SQL string expression, String) to convert a SQL string to a Visual Basic string, and CType(Visual Basic string expression, SqlString) to convert in the other direction.

' Insert the following line at the beginning of your source file.
Imports System.Data.SqlTypes

  Public Sub setJobString(ByVal g As Integer)
      Dim title As String
      Dim jobTitle As System.Data.SqlTypes.SqlString
      Select Case g
          Case 1
              title = "President"
          Case 2
              title = "Vice President"
          Case 3
              title = "Director"
          Case 4
              title = "Manager"
          Case Else
              title = "Worker"
      End Select
      jobTitle = CType(title, SqlString)
      MsgBox("Group " & CStr(g) & " generates title """ &
            CType(jobTitle, String) & """")
  End Sub

The SqlString structure defines a conversion operator (CType Function) from String to SqlString and another from SqlString to String. The statement that assigns title to jobTitle makes use of the first operator, and the MsgBox function call uses the second.

Be sure the class or structure you are using defines the operator you want to use. Do not assume that the class or structure has defined every operator available for overloading. For a list of available operators, see Operator Statement.

Include the appropriate Imports statement for the SQL string at the beginning of your source file (in this case System.Data.SqlTypes).

Your project must have references to System.Data and System.XML.

Operator Procedures
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
Widening
Narrowing
Structure Statement
How to: Declare a Structure
Implicit and Explicit Conversions
Widening and Narrowing Conversions

Show: