Casting in Visual Basic .NET

In all type safe languages there is the concept of “casting”, an operation used to specify to the compiler that a variable of a certain Type has to be considered of different Type. Visual Basic has three operators to do a cast: DirectCast, CType and TryCast, each one behaving in a different way from the other. To understand the subtle differences from these three operators lets present a simple example.

   Private Sub DirectCastExample(ByVal obj As Object)
      Console.WriteLine(
“string lenght={0}”, DirectCast(obj, String).Length)
   
End Sub
 
   
Private Sub CTypeExample(ByVal obj As Object)
      Console.WriteLine(
“string lenght={0}”, CType(obj, String).Length)
   
End Sub
 
   
Private Sub trycastExample(ByVal obj As Object)
      Console.WriteLine(
“string lenght={0}”, TryCast(obj, String).Length)
   
End Sub

   Private Sub Test()
      DirectCastExample(30)
      CTypeExample(30)
      trycastExample(30)
   
End Sub

The three instruction of the Test() function give really three different results, the first throws an InvalidCastException, the second writes “string length=2” and the third throws a NullReferenceException. To understand what is happening we could look at generated MSIL . DirectCast operator is translated with this code

L_0007: castclass string
L_000c: callvirt instance int32 [mscorlib]System.String::get_Length()

DirectCast is translated to castclass opcode, that simply pushes on the stack the object reference to the cast instance. If at run time the instance passed to the function is not a String class an InvalidCastException is thrown. DirectCast can convert if the object is of the exact type, if inherits from the type specified, or if the object implements the interface when the destination type is an interface.

TryCast operator behaves a little different, this is the MSIL generated

L_0007: isinst string
L_000c: callvirt instance int32 [mscorlib]System.String::get_Length()

TryCast use the isinst opcode, that is analogous to castclass, but if the cast is not successful instead of throwing an exception a null value is push on the stack. The third type of cast, CType is not really a cast operator, but instead a conversion operator, even if in a lot of documentation CType is considered to be a cast operator, to understand the difference here is generated MSIL.

L_0007: call string [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions::ToString(object)
L_000c: callvirt instance int32 [mscorlib]System.String::get_Length()

As you can see CType operator calls internally the function ToString() of class Microsoft.VisualBasic.CompilerServices.Conversions, this means that CType does not make a cast, but it makes conversions. The example in fact reveals that when we pass the integer value 30 to the function, this value gets converted to the string “30” and the code does not throw errors. The annoying issue is that you use CType to convert a variable to a custom type class it defaults to use castclass opcode, since the Microsoft.VisualBasic.CompilerServices.Conversion has methods to convert only to .NET basic types.

Alk.

Â

Â

Windows vista and the nostalgic users of command line :D

I needed to copy the windows sdk file (1.2 Gigabytes) from the desktop pc to my laptop, via Ethernet 100 mbps. I begin navigating to the network folder and try to right click the file to select copy. The result is that my laptop get hung….after some while I realized that my antivirus is trying to scan the network file to see if the file is virus free…I immediately terminate the antivirus, and change the option not to scan network files. Then I try to copy the file again, this time I was able to right click and copy the file, I went to destination folder and then do right click, then paste….a message box appears and the file starts to transfer……but my pc is still hung, after 2 minutes the progress bar is about at 15%, so I manually disconnected network cable, the operation was aborted and I decided to open a dos prompt box an type

copy “\\athlon\Download old H\developer\WinFx\OfficialRelease\6*.*”

after 2 minutes the file was on my laptop, but then I decided to move into another folder of the same partition, again I tried to do this through the windows shell, again a progress bar appears telling me something like “calculating time needed to perform the operation”……WHAT???? I was trying to move a file between folder in the same partition…again I stopped the operation, goes again in dos prompt and typed

move 6.0.6000.0.0.WindowsSDK_Vista_rtm.DVD.Rel.img f:\download\WindowsSDK\

The file was moved instantaneously. This poses a question…why these simple operations are really overkill when managed by windows vista shell and are extremely efficient when performed from a dos shell? Whell….I must admit that I’m a nostalgic command shell user J

Alk.

Subversion Versus Team Foundation

This morning I was reading this post, and I must admit that even I with my AbstractView project use Subversion (Google Code) to keep track of the sources of the project. Team Foundation Server and the features exposed through codeplex are really amazing, but when it is time to speak about Source Control I think that Subversion is a product really superior.

I use Subversion not only with Google Code but also with a dedicated server to keep all the source code of the company where I work. Subversion has great performance, it has high integration with the shell (Thanks to Tortoise), has really a lot of options. To be operative with subversion you have to download a little more than 10 mb opposed to 140 mb or more that you needs to download to integrate with codeplex.

In my opinion Subversion is probably the most interesting source control system, and it’s freeware :D

Alk.

Syntax vs Semantic

Yesterday I was reading a post of a friend of mine. In this post my friend complains that these two snippet of code produces very different result.

‘VB code: returns 1.2
Public Function TestDiv() As Double
Dim a As Int32 = 12
Dim b As Int32 = 10
Return a / b
End Function
//C# code: returns 1
public static Double TestDiv() {
Int32 a = 12;
Int32 b = 10;
return a / b;
}

This example opens up a little discussion on witch of the two behavior is the more “correct one” and makes me thinks about programming languages. A programming language is mainly composed by Syntax and Semantics, but it is surprising that a lot of people consider only the Syntax part when they switch from a language to another, ignoring semantics issues. The preceding examples is a perfect situation in which a programmer translate VB code into C# but forget to thing about how the languages interprets the code. But the question is, why languages have different semantics? Why C# returns 1 from the preceding function when a value of 1.2 would be more intuitive? Let’s make some thinkings…

Visual Basic .NET is very different from the older version (VB6 and previous version), but when the redmontonians creates is, they should maintain base semantics when possible. Visual Basic is a language born to be simple, its purpose is to permit to everyone to write a program. The result is that Visual Basic does not requires an intimate knowledge of the art o programming, so when a people write previous snippet, Visual Basic use floating point division even if the programmer ask to divide two integer values. The semantic of Visual Basic is to use the most detailed operation (floating point division) to shield the programmer from the gritty details of the processors.

C# is born from Java and C++, so people programming in these languages are used to know low level details about processors and virtual machines. C# enforces type safety, so when the compiler sees a division from two integers, it use integer division. This is the most logical semantic, if you divide two integer use integer division. Moreover the floating point division is slower in execution and this enforces C# compiler to have this semantic. The good thing is that both languages have Syntax that permits to choose which operator to use.

‘VB code: returns 1
Public Function TestDiv() As Double
Dim a As Int32 = 12
Dim b As Int32 = 10
Return a \ b
End Function
//C# code: returns 1.2
public static Double TestDiv() {
Int32 a = 12;
Int32 b = 10;
return (float) a / b;
}

Visual basic has operator \ , integer division, while C# requires only a cast. The C# approach is cleaner and according to me semantically more intuitive. If you divide two integer use integer division, if I tell the compiler to treat one of the number as float use the floating point division. Visual Basic on the other side introduces a whole new operator, only to express the concept of Integer Division, a solution that is less intuitive respect of C#.

The conclusion is that when moving from a language to another, be sure to keep in mind that is not only a change of Syntax, but be sure to take into account the semantic of new language.

Alk.