Monthly Archives: February 2011

A GOSUB By Any Other Name

Filed under .NET, Rants, VB Feng Shui

imageI’ve been using VS2010 for a while now, and there’s definitely a lot to like in this release. Granted, the UI is a little slower than 2008, but that’s mostly because of all the new WPF goodness baked into every nook and granny of the IDE now.

One thing that I’d been looking forward to is multi-line lambdas in VB. C# has had that since 2008 (or possibly before), but VB was always limited to a single line or (more typically) a call to a function, which could be multiline.

Still, when you’re talking about lambdas, you’re typically talking about small chunks of code that you almost never really want to be a separate function, Private or not. It’s just that much more clutter.

VB2010 finally addresses that disparity and you can now do multi-line lambdas in VB.

Dim MyLambda = Function(arg As String) As String
   arg &= ","
   arg &= "More"
   Return arg

'And to call it

Now, technically speaking, you might argue that “MyLambda” is an anonymous method. And you’d be right. Anonymous methods, delegates, and lambdas are, essentially, different names for the same thing. Basically, they’re all just ways of “embedding” code into a variable, and then being able to call that code.

In the olden days, you’d use pointers for such folderol, but this is managed .net code, and pointers are all but verboten in these parts.

But wait!

The thing is, it struck me at one point, while recently describing how you might actually use a delegate to a colleague, of the similarities between anonymous functions like the above, and the much maligned VB GOSUB statement (GOTO’s less recognized little brother).

Dim Arg as string = "testArg"
Gosub MyLambda

   arg &= ","
   arg &= "More"

Don’t get me wrong, I never found GOSUB to be particularly all that clean a construct. I used it on occasion, but not often. You couldn’t pass explicit arguments with GOSUB, and executing a variable GOSUB required the ON x GOSUB statement, which was pretty abysmal to use.

Still, all the makings of a lambda were right there, all along.