SyntaxDim result As typename = CType(expression, typename)
DescriptionThe CType function converts an expression or object to the specified type. Usage at a Glance
ExampleEach list item added to a Windows Forms ListBox control includes an object of any type that is used to both display the text and store custom user data. Internally, it is stored as Object. When you retrieve the data object for a single list entry, you must convert it to the original type before using its members. This example defines a simple form with a ListBox. When an item is selected, the data associated with the selected item is cast back to a TeamDetails object. Public Class BaseballTeams Inherits System.Windows.Forms.Form ' ----- Define a simple class to store in the list. Protected Class TeamDetails Public TeamName As String Public Members As Integer Public Sub New(ByVal fullName As String, _ ByVal totalMembers As Integer) ' ----- Simple constructor. TeamName = fullName Members = totalMembers End Sub Public Overrides Function ToString( ) As String ' ----- Properly displays information in list box. Return TeamName & " (" & Members & ")" End Function End Class Private Sub BaseballTeams_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' ----- Add some basic teams. TeamNames.Items.Add(New TeamDetails("Tokyo Giants", 18)) TeamNames.Items.Add(New TeamDetails("Seattle Mariners", 20)) End Sub Private Sub TeamNames_SelectedIndexChanged( _ ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles TeamNames.SelectedIndexChanged ' ----- To display the details, we must convert the type. Dim selectedTeam As TeamDetails selectedTeam = CType(TeamNames.SelectedItem, TeamDetails) MsgBox("Team = " & selectedTeam.TeamName & vbCrLf & _ "Members = " & selectedTeam.Members) End Sub End Class Version Differences
See AlsoCBool Function, CByte Function, CChar Function, CDate Function, CDbl Function, CDec Function, CInt Function, CLng Function, CObj Function, CSByte Function, CShort Function, CSng Function, CStr Function, CUInt Function, CULong Function, CUShort Function |