Code Focused

What's New in Visual Basic 2010

With the release of Visual Studio 2010 and the .NET Framework 4, it's time for Visual Basic developers to start leveraging the new capabilities of Visual Basic 2010.

My very first learning experience with computers involved HP BASIC on a DEC Teletype that had no screen and could only print interactions on 14-inch-wide green bar paper. During my high school years in the late 1970s, I'd stay after school while a friend went to football or basketball practice, spend hours on the school's only computer terminal, and then catch a ride home with him after practice. I printed out the HP Basic source code for simple games like Tic-Tac-Toe or Hangman and read it over and over again until I was able to fully understand the programming logic.

I couldn't have been happier -- I understood a secret language that no one else in my class even knew existed, and I could make this amazing computer terminal device do my bidding with just a few lines of code. Some 30 years later at our high school class reunion, I profusely thanked Chris Parker, the classmate who had taken me home each night, for helping me establish a great career and a lifelong love for the art of software development. Then I asked for a ride home.

Software development in some version of BASIC has been a part of my career ever since high school. Along the way I wrote programs in other languages such as FORTRAN, Pascal, APL and even COBOL, but none of those languages had the natural expressiveness and ease of use of BASIC. Microsoft continues to build on those attributes with the release of Visual Basic 10. The C# and Visual Basic language teams were merged in 2008 and Visual Basic 2010 represents the first release of Visual Basic from the Visual Studio managed languages team. Enhancements to both C# and Visual Basic reflect the team's commitment to co-evolution of functionality across both C# and Visual Basic languages.

As my first On VB column coincides with the recent release of Visual Basic 2010, Visual Studio 2010 and the Microsoft .NET Framework 4, I thought I'd go over the new features of Visual Basic 2010.

Implicit Line Continuation
The most striking thing when looking at Visual Basic 2010 code is the lack of line-continuation characters. At last we can use long and expressive method and variable names in statements that span several lines without constantly holding down that annoying shift key to type the underscore line-continuation character, as shown in Listing 1. While code with implicit line-continuation characters is functionally equivalent to code with line-continuation characters, it just removes a lot of unnecessary noise from the code and makes the source code even more readable. C# developers have enjoyed this benefit from the outset, and finally Visual Basic developers have it as well.

Auto-Implemented Properties
Auto-implemented properties simply describes the new one-line statement for properties that store and retrieve data and don't do any special processing during the get or set operation. Because the majority of properties in a typical application fall into this category, this can be a real time-saver. C# has had this feature since version 3.0 was released in November 2006. Examples for Visual Basic auto properties, C# auto properties and the full Visual Basic property syntax are shown in Listing 2.

Visual Basic 2010 auto-implemented properties may be initialized to a default value with the "= value" syntax (see Listing 2). The compiler automatically generates a private backing field with the same name as the property but with a leading underscore. By having a predictable backing field name, Visual Basic auto-implemented properties can be later converted to standard properties with processing logic in the get or set operations. As long as the now-explicit backing field is declared as "_propertyname," it won't be a breaking change with the auto-implemented version of the property.

Because the syntax for auto-implemented fields is so similar to public fields, you may be tempted to use them instead. It's important to continue to use properties rather than public fields for many reasons, including data-binding, enforcing interfaces and having the flexibility to change the property's operation -- something you can't do with a public field.

Collection Initializers and Lambda Expressions
Collection initializers are just that -- the ability to initialize a collection at the time of its declaration. The Add statement is automatically added by the compiler for each element of the collection being initialized. The Visual Basic 2010 syntax is shown in Listing 3 on the left; the equivalent C# syntax is shown on the right. Collection initializers are also available for more complex types, such as dictionaries. You can even use collection initializers with your own types, as long as you create an Add extension method that properly initializes an instance of your collection element.

Visual Basic 2008 introduced single-line Lambda expressions (functions) to support LINQ. Visual Basic 2010 supports lambda statements (subroutines) and multi-line strings. As before, a lambda is defined only within its current scope. The following code shows a multiple-line statement lambda that displays the sum of an array of integers with a MessageBox:

    Dim ArraySum = Sub(IntArrray() As Integer)
                       Dim Result As Integer = 0
                       For Each i As Integer In IntArrray
                        Result += i
                       Next
                       MessageBox.Show("Sum of Array is " + 
				     Result.ToString)
                   End Sub
    Dim SingleDigits() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    ArraySum(SingleDigits) 'Sum of Array is 45 MessageBox

Covariance and Contravariance
A derived type is a type that has inherited or derived from another type. Visual Basic 2010 introduces covariance (which allows you to use a derived type in place of a less-derived or parent type), and contravariance, which is the reverse (allowing you to use a less-derived type in place of a derived type). For example, consider type BookStore that inherits or derives from the more general RetailStore. In the appropriate situations, covariance allows you to use an instance of BookStore in place of RetailStore, and contravariance allows you to use an instance of RetailStore in place of BookStore. This is one of the enhancements that is being added simultaneously to both C# and Visual Basic with the release of Visual Studio 2010.

The first statement in the following code will generate an invalid implicit conversion error in Visual Basic 2008 (Visual Basic 9) with Option Strict On. The same statement will work fine in Visual Basic 2010 because the interface IEnumerable is now variant, meaning that it supports covariance. The second statement will still generate a compile error in Visual Basic 2010 because even though List implements the now-variant IEnumberable(Of T) interface, List is a class and is not variant:

'Generates a compile error in VB 2008 with Option    
'Strict On but not in VB 2010
Dim Stores As IEnumerable(Of RetailStore) = 
 New List(Of BookStore) 'Covariance

'Generates a compile error in VB 2010 with Option 'Strict On because List() is not variant
Dim MyStores As List(Of RetailStore) = 
 New List(Of BookStore)

Additional variant interfaces include IQueryable(of T), IGrouping(Of TKey, TElement), IComparer(Of T) and IComparable(Of T). The Func(Of TResult), Action(Of T), Predicate(Of T), Comparison(Of T) and Converter(Of TInput, TOutput) delegates likewise have been marked variant in Visual Basic 2010.

Generic delegates can now be made variant; that is, Visual Basic 2010 now supports variant generic delegates. Note that ByRef parameters can't be marked variant. Covariant parameters are marked with the "Out" modifier, and contravariant parameters are marked with the "In" modifier. They can be combined, but not on the same parameter. See the following code for a delegate statement that combines a covariant and contravariant parameter with the required non-variant return type:

    Public Delegate Function Variants(Of In BookStore, 
      Out RetailStore)(ByVal param As T) As R

The full details of covariance and contravariance are rich topics, and a full discussion is outside the scope of this article. For the most part, you won't need to pay much attention to them. Code that used to require a call to Cast(Of T) will just work now with a more natural code appearance. The topic of covariance and contravariance was also covered in a C# Corner column, "Generic Covariance and Contravariance in C# 4.0" (May 2009).

Type Equivalence Support
A Primary Interop Assembly (PIA) is a vendor-supplied assembly for a COM application that contains the type definitions or metadata for a .NET application to have a more convenient and richer interaction with the application. Visual Basic developers are probably most familiar with the Microsoft Office PIAs that have been available since Office XP.

Microsoft strongly encourages the use of these PIAs over any COM interop assembly that's generated by Visual Studio at design time. Applications developed with the Microsoft Office PIAs have to ensure that the client has the PIAs available, either by including them in their Setup & Deployment package or ensuring that the client has already installed the Redistributable PIA for the target version of Office. Previously, including these assemblies in your application added megabytes of bulk, even if only a few functions were used. For applications deployed over the Internet, this was a significant disappointment.

Microsoft has addressed the concern regarding PIA size by introducing Type Equivalent Support in Visual Basic 2010 and C# simultaneously. This is an under-publicized enhancement, but truly a tremendous boon for users of PIAs. The external types used by the application -- and only those types -- are compiled into the application's assemblies, eliminating the need to deploy PIAs and increasing the application's footprint by only the size of the imported types actually needed to perform the needed functions. For all practical purposes, this eliminates the deployment concerns of using PIAs for COM applications.

For new applications, Type Equivalence Support is already enabled. For applications upgraded to Visual Basic 2010, you need to enable Type Equivalence Support. For each PIA reference in the application, select the reference and in the Properties window, change the Embed Interop Type setting to True. Remove any PIA deployment process you already have. It's that easy.

If you're compiling your application via the command line, you can use the /link switch instead of the /reference switch.

Dynamic Support
Visual Basic 2010 adds late-binding support to the Dynamic Language Runtime, which offers access to objects from dynamic languages such as IronPython and IronRuby. Simply create an instance to the runtime of the desired dynamic language in order to access its features using standard Visual Basic syntax.

There are also new command-line options for specifying language version. With the exception of Type Equivalence Support and the newly variant classes like IEnumerable, the enhancements listed in this article are available to the Visual Basic developer even when targeting a prior version of the .NET runtime. Because you'll want to do as much of your development in Visual Basic 2010 as you can, you can target an older runtime in Visual Studio by going to your Project, right-clicking and then selecting Properties, Compile tab and Advanced Compile Options, and then selecting the desired target framework.

Targeting the framework in Visual Studio doesn't limit the syntax to only statements that were valid at that level of the framework. Use the /langversion command-line option to generate errors for syntax that's valid only above the desired framework level. For example, the following command line will compile myclass.vb and generate errors for any syntax that's valid only for Visual Basic 2010:

Vbc /langversion 9.0 myclass.vb

Visual Basic 2010 is an exciting release, and I'm happy to introduce it to you. Chris Parker, I'm ready for that ride home now.

comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.