DirectCast V CType

hog

Senior Contributor
Joined
Mar 17, 2003
Messages
984
Location
UK
Can some explain in laymans terms the difference between the to convertion keywords please.

I think I have it but just want to be sure. The help says

Dim Q As Object = 2.37
Dim I As Integer = CType(Q,Integer)
Dim J as Integer = DirectCast(Q,Integer)

I succeeds as 2.37 converts to an Integer...

J fails as Q was declared as an Object not an Integer so DirectCast fails.

Question is why use DirectCast instead of CType

Apologies incase this is a stupid question
 
DirectCast is used to cast from one class to a sub or superclass of that type. The Convert class is used to convert one type to another, for example "3.141" to 3.141.

The CType function is a VB helper designed to decide which one to use. I avoid it as it isn't available in any other language.
 
Back
Top