Source Code: How To Improve Performance with TryCast Keyword VB2005
How To Improve Performance with TryCast Keyword VB2005
The TryCast keyword, introduced in Visual Basic 2005, provides Visual Basic programmers with a new way to cast reference types.
Unlike the CType and DirectCast keywords, if an attempt to convert with TryCast fails, TryCast will NOT throw an InvalidCastException error. This will improve the performance of your application.
TryCast returns Nothing if a conversion attempt fails. Instead of having to handle a possible exception, you need only test the returned result against Nothing.
You use the TryCast keyword the same way you use the CType Function and the DirectCast keyword. You supply an expression as the first argument and a type to convert it to as the second argument.
TryCast operates only on reference types, such as classes and interfaces. It requires an inheritance or implementation relationship between the two types. This means that one type must inherit from or implement the other.
Example Application Screen Shot

Source Code Excerpt
Private Sub RunDemoButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RunDemoButton.Click
Me.ResultsRichTextBox.Clear()
' Declare variable named textBox1 of type TextBox.
' Call the TextBox class' New method; assign a reference
' to the resulting TextBox object to the textBox1 variable.
Dim textBox1 As New TextBox
' Declare variable named obj of type Object.
Dim obj As Object
' Assign a reference to the object referenced by the textBox1 variable to the obj variable.
obj = textBox1
' At this point:
' textBox1 references a TextBox object as type TextBox
' obj references the same TextBox object as type Object.
Me.ResultsRichTextBox.AppendText("Attempting to cast object as TextBox..." & vbCrLf)
' Declare variable named textBox2 of type TextBox.
Dim textBox2 As TextBox
' Try to cast the object referenced by the obj variable as a TextBox.
textBox2 = TryCast(obj, TextBox)
If textBox2 IsNot Nothing Then
Me.ResultsRichTextBox.AppendText("Object was successfully cast as type TextBox." & vbCrLf & vbCrLf)
Else
Me.ResultsRichTextBox.AppendText("Object could not be cast as type TextBox." & vbCrLf & vbCrLf)
End If
Me.ResultsRichTextBox.AppendText("Attempting to cast object as Button..." & vbCrLf)
' Declare variable named button1 of type Button.
Dim button1 As Button
' Try to cast the object referenced by the obj variable as a Button.
button1 = TryCast(obj, Button)
If button1 IsNot Nothing Then
Me.ResultsRichTextBox.AppendText("Object was cast as type Button.")
Else
Me.ResultsRichTextBox.AppendText("Object could not be cast as type Button. However, no exception was thrown by the attempt to cast it, as would have been the case if DirectCast would have been used.")
End If
End Sub
For more information:
TryCast Keyword
mike mcintyre http://www.getdotnetcode.com