dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: .NET
Expertise: Beginner
Aug 29, 2016

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


When to use CType, TryCast, DirectCast, CBool, etc.

When you need to cast some type to another type in VB, you should favor the "classical" functions CBool, CByte, CInt, CLng, CDec, CSng, CDbl, CDate, CStr and the "new" kids on the block (CSByte, CShort, CUShort, CUInt, CULng, CChar, and CObj) as they were designed exactly for it.

If you need to change, say, an Object that you know contains an array of bytes (or a nullable type, like Boolean?) to a proper array of bytes, then your choice should be CType, as there are no CBytes or CArrayOfBytes function... :)

If you are not sure the Object actually contains an array of bytes, using CType is not the best option, as it could throw an exception if your variable is not convertible to the destination type. In this case you should use TryCast: If the cast succeeds, you get your array of bytes. If it doesn't, then you get Nothing instead.

But when casting instances of objects to interfaces or to other classes, then you best bet is DirectCast. It is faster than CType, but if you are not sure the conversion will succeed, then you should still use TryCast.

Oracy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date