Sunday, February 13, 2005
unboxing in VB is different than C#
another point for VB against C#
let's do this example :
in C# :
int i = 7;
myObj = (object)i; //boxing
long j = (long)o; //InvalidCastException
the CLR will only let you convert it back to Integer
in VB :
Dim i As Integer = 4
Dim myobj As Object
myobj = i 'boxing
Dim j As Long = CType(myobj, Long) 'unboxing works fine
Dim k as long = DirectCast (myobj, Long) 'Generates an error coz DirectCast Bypass VB Helper Funs
How is Works :
To make this work, the compiler emits a conversion from Object as a call to a helper function. The helper function takes the Object, looks at the type of the value contained in it and then does the appropriate conversion to the target type. this means an extra step . it might be an extra step in the wrong direction in case i know the returned type , so i will only lose some performace.
so the Rule is : if i know the result TYPE i would use DirectCast which bypasses the VB helper functions , and i get some performance gain .
as you see , the Default is the helper funs , so the language by default (cint , clong , ctype , etc ... ) can unbox to any type unless you need to switch off this nice feature using DirectCast .
this means that , it is not possible to express all VB language in IL . there are some helper functions like Late Binding ( i will take about this later in coming post) which is not found in IL . that's why we need Microsoft.visualbasic.dll in all the VB projects and we cannot remove that reference .