RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

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

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.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date