Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Dynamic Typecasting

VB6 supported variant types and it was common to see code that depended on late bound objects.

VB6 and Visual Basic .NET support two kinds of reference use, early bound and late bound. Early bound references are references where the type of the object is known or resolved programmatically. Late bound references are resolved at runtime. Code like the following example relies on late binding:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles TextBox1.TextChanged

 MessageBox.Show(sender.Text)
End Sub

Clearly, sender is an Object type and Object does not have Text member. Because the Handles TextBox1.TextChanged clause indicates that the event handler responds to a Changed event for TextBox1, this code is reasonable. To revise this example to demonstrate early binding, we use the CType method to cast the type of sender to the correct type:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles TextBox1.TextChanged

 MessageBox.Show(CType(sender, TextBox).Text)
End Sub

Now the compiler can check to make sure that Text is a member of the target type, TextBox.

You are encouraged to use early binding in Visual Basic .NET. You can enforce early binding with Option Strict On. Using early binding means that you will have to use the more verbose form of the call, performing dynamic type casting. Using Option Strict On will ensure that inappropriate member usage will be caught at compile time and you will get a trappable System.InvalidCastException when you attempt to cast a generic type to a specific type and the instance is not an instance of the specific type (see Figure 10.6).

Figure 10.6 Casting to an invalid type will result in a catchable exception.

NOTE

Visual Basic .NET supports late binding to public methods only. You may not perform late binding on nonpublic methods or interface methods.

Verbose explicit code is preferable in Visual Basic .NET. Set Option Strict On and use the CType function to dynamically cast a more general type to a specific type.

  • + Share This
  • 🔖 Save To Your Account