.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

DirectCast better than CType in VB

Posted By:Deepika Haridas       Posted Date: October 13, 2010    Points: 15    Category: Visual Studio    URL: http://www.dotnetspark.com  

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.
 

     

Further Readings:

    Responses

    No response found. Be the first to respond this post

    Post Comment

    You must Sign In To post reply
    Find More code samples in C#, ASP.Net, Vb.Net and more Here

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend