Sunday, April 24, 2011

VB.NET finally gets the Yield statement

I've found myself multiple times in the last four years having to defend Visual Basic against the disgusted reactions of some of my C# developer friends.  I think most people who have to pinch their noses at the term "VB" aren't really doing it towards the language, but more towards the stereotypical perception of a what they believe to be the quality of VB developers in general.  It's easier to argue technical merits than stereotypical opinion, other than to say that good developers are versatile and objective when evaluating technologies and each other.

I admit that it took me about a week or two when I first started to swallow my pride and accept that we have a pretty extensive codebase written in VB, and there's very little compelling reason to change it.  And now, I actually really enjoy it almost as much as C#... except for lambdas... ug, so verbose.  Anyway, over time C# and VB have converged and the similarities far outweigh the differences.  If you can do it in C#, you can almost certainly do it in VB with a few notable exceptions.  In fact, since getting auto-properties and option infer, lately I've been describing VB thusly:

VB really is no different than C#.  You have all the same libraries.  It's a little bit more verbose in places, but a lot more readable in others.  Once you get used to case-insensitive languages, you'll wonder why there aren't more of them out there.  The only features you might miss are the dynamic and yield keywords, and unsafe if you ever use it (which you shouldn't be).  Actually, dynamic features have been available in VB since the beginning, but they are file scoped instead of variable scoped.  So Yield is really the only thing you'll wish you could do, but can't.

And now, at long last - with the new Microsoft Visual Studio Async CTP (SP1 Refresh), we've finally gotten a Yield keyword in VB.  This changes my whole elevator pitch.

I've installed it, and toyed with it, and it works exactly as you'd expect.  Here's the arbitrary infinite Fibonacci sequence hacked together in 30 seconds in VB:


Module Module1

 Sub Main()
  For Each i In GetFib()
   If i > 500 Then Exit For
   Console.WriteLine(i)
  Next
  Console.WriteLine("Done...")
  Console.ReadKey(True)
 End Sub

 Public Iterator Function GetFib() As IEnumerable(Of Long)
  ' Forget math overflow... this is only a test
  Yield 0
  Yield 1
  Dim previous = 0, current = 1
  While True
   Dim nextVal = previous + current
   previous = current
   current = nextVal
   Yield current
  End While

 End Function

End Module 

It's only 6 years overdue, but still such a welcome addition to the VB family. I can now finally get rid of my bloated iterator classes for my OrderedDictionary and my TreeNode classes. I can start porting projects like Dapper to VB without bloating the code. Thank you Microsoft. You've made my work life so much less painful.