DirectCast better than CType in VB


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

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.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: