RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Fall In Love with Visual Basic All Over Again in Visual Studio 2008 : Page 4

Discover anew why Visual Basic is one of the most successful programming languages in history by exploring some of the new features Microsoft added to Visual Studio and Visual Basic.

Object Initializers
VB9 provides a new syntax for initializing objects. In past versions of VB, if a constructor was unavailable or couldn't initialize an object completely, you had to finish initialization after creating the object. I have run into more than one instance where code was later inserted between when the object was created and when its initialization was completed, resulting in unanticipated object behavior. The code sample below demonstrates two common ways of initializing an object in older VB versions.

   Dim obj1 As New DataLayer
   obj1.FirstName = "Michael"
   obj1.LastName = "Jones"
   ' OR 
   Dim obj2 As New DataLayer
   With obj2
       .FirstName = "Michael"
       .LastName = "Jones"
   End With
VB9's new method is a bit ungainly, but ensures that the new object gets initialized in a way that is more difficult to interrupt. Interrupting the object's initialization would require a developer to make a conscious decision to modify the initialization code because the new initialization syntax makes it clear that object creation and object initialization should happen together. Here's an identical initialization using the new syntax:

   Dim obj3 As New DataLayer With _
       {.FirstName = "Michael", .LastName = "Jones"}
Both the old and new methods result in identical compiled code; the new syntax is merely more concise—and perhaps more self-documenting in some cases.

This feature is available regardless of the framework version you target. I recommend using this method of initializing objects unless the number of fields to be initialized makes the code more difficult to read.

Implicit Types
Also known as Local Type Inference, implicit types are among my least favorite features of VB9. This feature allows VB9 to determine the type you are declaring without you having to explicitly declare the type. My main fear with widespread use of this feature is a loss of readability.

Microsoft clearly added implicit types to make LINQ more powerful, but I think this feature is best left alone outside of LINQ. It uses the expression's type to correctly determine the type of the new variable. If the variable is not initialized when it is created, the compiler will dimension it as an Object. In the code fragments below, contrast the VB8 style of explicitly declaring types with the less rigid declaration style supported by VB9, where no types are specified.

   Dim age As Integer = 65
   Dim name As String = "Michael Jones"
   Dim things As New List(Of String)
   Dim vb9_age = 65
   Dim vb9_name = "Michael Jones"
   Dim vb9_things = New List(Of String)
However, fear not, VB9 gets the type right—almost all the time. In the sample project, hover over the VB9 variable declarations in the btnImplicitTypes_Click method call. The tooltip shows that VB9 knows that vb9_age is an Integer and that vb9_name is a String.

But you can run into trouble in two common cases if you allow VB9 to infer the type. These are:

  1. When there are multiple types that are suitable, such as Integer and Long (the default in this case is Integer)
  2. When you want to create a derived type and declare it as a base type. In such cases, you must provide an explicit variable type in the declaration.
Another instance where you might use implicit types is in a For Each loop. As shown in the code sample below, VB9 correctly determined that the variable thing is a String because it's used in a For Each construct where the target is a List(Of String).

   For Each thing In vb9_things
Here again, I think it is worth providing the index variable's type to make the code more readable. I suggest you shy away from this feature. It doesn't add any compelling productivity features and can only serve to make your code less readable.

Anonymous Types
My least favorite of all the new features in VB9 is anonymous types. Like implicit types, this feature was added expressly to support LINQ. Used without LINQ, this feature is nothing but trouble. I do not recommend it because it decreases code readability.

Anonymous types allow developers to create structure-like objects without giving them an explicit name or definition. This feature is used in combination with implicit types to declare variables where the type name is not specified. LINQ uses anonymous types to create types for LINQ query results. Since the type structure is derived from the LINQ query, it changes based on the content of query. Since there isn't an intuitive way to define the structure a priori, anonymous types were introduced to solve the problem.

I have provided some sample code below to demonstrate the use of anonymous types. Notice: In addition to the lack of a type name there is also no explicit reference to a pre-defined type. However, as you will see, if you step through the code in the sample project, VB treats the types and variables just as you would expect.

   'Notice, no declaration type name
   Dim theArticle = New With _
       {.Name = "Michael Jones", .ArticleTopic = "Visual Studio 9"}
   'VB created a type and 
   txtResults.Text = theArticle.Name & vbCrLf
   txtResults.Text += theArticle.ArticleTopic & vbCrLf
   txtResults.Text += "Type name: " & theArticle.GetType.ToString()
   txtResults.Text += vbCrLf
If you are still a little curious about this, notice the tooltip Visual Studio provides when you hover over the declaration of theArticle in the code above (see Figure 9).

Figure 9. Anonymous Type Tooltip: Visual Studio displays a tooltip that lets you know when you're inspecting an anonymous type.
When you run the code, Visual Studio displays the run-time name of the type VB assigned to the anonymous type as: VB$AnonymousType_0`2[System.String, System.String].

Anonymous types might be a good way to store temporary data. It is an easy way to build a data structure to store ad hoc data in your program. However, it seems only to save you the time of declaring the type (class or structure). I advise against using this feature in your projects. Take the time to create the structure you need and use the fully declared type instead.

Relaxed Delegates
Delegates are a mainstay of the .NET Framework; they're used to manage events and to provide an efficient and type-safe callback mechanism. In previous versions of VB, the compiler has strictly ensured that a delegate's method signature matches the expected signature—so you haven't been able to (for example) assign a method with a KeyPress event signature to a button's Click event; the method signatures of the two delegates don't match.

VB9 relaxes the enforcement of delegate signatures, so you can now use a single method to handle both Click and KeyPress events from a button. Further, if you don't need the arguments, you can eliminate them from the method signature. The code fragment below shows a single method that handles Click and KeyPress events for the button named btnRelaxedDelegates. Notice that the parameters have also been removed to add a bit of implicit documentation, showing that the method doesn't need the standard parameters:

   Private Sub btnRelaxedDelegates_EventHandler() _
       Handles btnRelaxedDelegates.Click, btnRelaxedDelegates.KeyPress
       txtResults.Text += Now.ToLongTimeString & vbCrLf
   End Sub
As with some of the others, I am a bit torn about whether I like this feature. I do like the idea of improving code sharing; bit it only saves you from having to call a common method from both event handler methods. It feels somewhat inappropriate because of the potential to cause confusion make the code base less maintainable. I will choose to shy away from this feature.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date