Implicitly Typed Local Variables in VB9

At first glance, the new ImpliciltyTyped Local Variables in C#3.0 and VB9 might look familiar to VB programmers.

Earlier (that would be “current” as well) versions of VB can do a lot of implicit stuff. This has been a point of aggravation to many non-VB programmers, but I guess they have a new perspective. Next thing you know they’ll be using declarative languages! Eek!

In VB2005, we can create an integer implicitly and do integer-like things with it.

  Dim ii = 5
  Console.WriteLine(ii + 2)

Or we can do the same with something more complex like a FileInfo class. I’m not explicitly declaring files, but VB infers it from what is returned by New DirectoryInfo.GetFiles (an array of FileInfo objects).

   Dim files = New IO.DirectoryInfo(“C:\”).GetFiles

We can even go a bit further with an iteration, using f to represent each FileInfo object without explicitly defining it.

   For Each f In files
       Console.WriteLine(f.FullName)
   Next

All of this runs just fine.

But, if you were actually typing this code, you would notice that the compiler does not comprehend the types at design time.

That’s because it can’t really identify the type at design time. All that’s happening here is that we are getting late binding.

The undeclared f (FileInfo) doesn’t even give you this much help with late binding. No method or property suggestions and it’s just an object.

So here is where VB9 is definitely different. We are truly getting strong typing, not just the intelligence of late binding.

When using the implicit variables in VB9, the compiler is smarter and much more helpful!

In the For Each, f is now recognized as a FileInfo and gives intellisense as well.

Note that all of this is using the default VS2008 properties for Compiler Options. Jim Wooley has an interesting blog post about Option Infer (a new option) which allows the strong typing to occur.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.