Compartilhar via


How to: Use a Class that Defines Operators 

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.

Example

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 (Visual Basic) call uses the second.

Compiling the Code

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. If you need to add them, see How to: Add and Remove References in Visual Studio (C#, J#).

See Also

Tasks

How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Declare a Structure

Reference

Widening
Narrowing
Structure Statement

Concepts

Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions