Oct 5, 2010

DirectCast better than CType

DirectCast

performs better than using CType when casting from an object to a more specific type because it does not use runtime helper functions.

The below example shows way to cast from type Object to another type with VB:

Private Sub txt_Submit(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtUId.Submit 
    DirectCast(sender, TextBox).BackColor = Color.Yellow
End Sub 


The DirectCast statement in this example casts the sender variable that is of type Object to a TextBox control in order to access the TextBox properties.

You can use DirectCast only when casting from a type to a related but more specific type, called a derived type. 

For example, you can use DirectCast to cast from type Control to type TextBox because TextBox is derived from Control. You cannot use DirectCast to convert from an Integer to a String type because String is not derived from Integer. DirectCast can always be used to cast from type Object to any other type because all other types derive from type Object.

No comments:

Post a Comment