Tuesday, 25 May 2010

Has VB come of age?

When .Net first came out I tended to use C# by choice, having a history of Java and C++, but I still retained an affection for Visual Basic. Most things could be done in VB rather than C#, but VB was always a little more verbose and had annoying features like having to type in space-underscore to carry a statement onto another line. Provided strict type checking was turned on though it gave the same performance as C#, and of course having been a Java enthusiast strict type checking in itself was very important to me.

This week I wanted to begin a project involving various forms of parallel execution. In the past I would have instinctively gone for C#, but having been training in VB for the previous couple of weeks I decided to begin with VB. And I found myself rather liking it, especially now I don’t need the space-underscores any more. I guess the first thing is that being able to do parallel programming naturally in VB was revealing – something that would have been assumed to be C++ territory a decade ago. But I also found that small changes from the last couple of versions appealed.

For example, let’s imagine that you are issuing an ADO.Net command and getting a data reader back. In 'VB6 style' this would be something like:

Dim cmd As New SqlCommand( sql, connection )
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader()

VB 200x of course allows 1 less line:

Dim cmd As New SqlCommand( sql, connection )
Dim rdr As SqlDataReader = cmd.ExecuteReader()

But the 2nd line feels a little unnatural to a Java mindset. Type inference allows:

Dim cmd As New SqlCommand( sql, connection )
Dim rdr = cmd.ExecuteReader()

Which is now as concise as it would be in C#. Type inference goes a bit further in VB than C#, for example:

Dim someList As New List(Of SomeClass)
For Each thing in someList

Next thing

Where in C# the type of ‘thing’ needs to be given such as:

foreach( SomeClass thing in someList ) { … }

which is not very different but some reason many people find the SomeClass thing confusing in training courses.

As a last example, this is a trivial example of a lambda in C# which shows a message box (for something to do!) from a thread:

Thread t = new Thread( () => MessageBox.Show( "text " ) );

The VB equivalent would be:

Dim t As New Thread(Sub() MessageBox.Show("text"))

I feel this is a case where the VB is more intuitive (and is actually less typing). But that’s just me.