Check out the new features in Visual Basic 10, the latest version of VB coming out with Visual Studio 2010 and .NET 4.0.

The majority of the new features in VB 10 focus on productivity. The new features allow you to write code with less typing. And I know we all want that!

This article details each of the primary new features in VB 10.

Implicit Line Continuation

How many times have you typed a space and an underscore (“ _”) when building your Visual Basic applications? Thousands? Millions? Consider how much time you could save in a year if you did not need to type them!

The implicit line continuation feature in VB 10 assumes a line continuation in most cases instead of requiring you to explicitly define that the statement continues onto the next line. No more typing endless underscores!

You can use implicit line continuation in the following cases:

  • After a comma
  • After an open parenthesis, open curly brace, or open embedded expression (<%=)
  • Before a closed parenthesis, closed curly brace, or closed embedded expression (%>)
  • After a concatenation operator (&)
  • After any assignment operator
  • After any binary operator, such as AndAlso or OrElse
  • After Is or IsNot operators
  • After a member qualifier character (.) and before the member name (unless it is part of a With statement)
  • After the attribute start character (<) or before the attribute end character (>)
  • Before or after query operators (LINQ)
  • After the “In” in a For/Each statement
  • After the “From” in a collection initializer

If you break a code line in any other location, you will still need to insert a line continuation character. Also, any line continuations you currently have still work, so you don’t need to go through your code and remove them.

The later code snippets in this article make use of implicit line continuations as an example of this feature.

No more typing endless underscores!

Auto-Implemented Properties

When you build a class, you define properties and methods. The properties access the data in your application and the methods perform the operations. In many cases, your property statements contain code to perform validation or formatting. But in some cases, your property setters and getters have no extra code. In the later case, you can save typing using auto-implemented properties.

This is easier to see with an example. Listing 1 shows a simple start for a Customer class without auto-implemented properties:

For each property, the code declares a private backing field and a property statement. The getter returns the value of the backing field and the setter sets the value of the backing field. Notice how the majority of the properties have no extra code in the getters or setters. Only the LastName property has implemented validation code. (For more information on building your own Validation class, see http://msmvps.com/blogs/deborahk/archive/2009/07/16/validation-class.aspx)

You can dramatically reduce the amount of code you write in this case by using auto-implemented properties. Listing 2 shows the same class using the auto-implemented properties feature for all but the LastName property. Since the LastName property requires extra validation code in the setter, it was not modified to use this new feature. The LastName property uses the standard, or expanded, property syntax.

Auto-implemented properties allow you to define a property without explicitly defining the getter and setter, saving you typing. The Visual Basic compiler automatically creates the backing field and defines the standard getter and setter in the compiled code.

The backing field created by the compiler is named with the same name as the property, prefixed with an underscore (“_”). So the backing field for the CustomerId property in the above example is _CustomerId. The backing field is accessible to debugging tools, such as the Watch window, but is not included in IntelliSense.

If you need a default value for the property, you can use an auto-implemented property as demonstrated with the State property in the prior example. Simply assign the property to the desired value.

You can use auto-implemented properties any time you have no extra code in your getters and setters. Use the expanded property syntax if you need extra code in your getters or setters, such as for validation, or if you need different accessibility on your getter and setter.

If you use an auto-implemented property and then later want to expand it, Visual Studio will expand it for you if you follow these steps:

  1. Ensure that there is a blank line after the property statement.
  2. Move the cursor to the blank line.
  3. Type “G” or “S” and then press Tab and then Enter.

This set of steps calls either the Get (“G”) or Set (“S”) code snippet, which creates the getter and setter for you. You can then add additional code to the getter or setter as needed. However, this does not automatically define the backing field. It may be faster to delete the auto-implemented property statement and use the property snippet, which defines the backing field and the expanded property statement.

Auto-implemented properties allow you to define a property without explicitly defining the getter and setter, saving you typing.

To use the property snippet, follow these steps:

  1. Move the cursor to a blank line.
  2. Type “property” and press Tab.

You can then fill in the appropriate placeholders to finish your property statement.

Collection Initializers

If you use generic lists, like the EmailAddresses property in the prior example, you have to initialize the list and then add each entry to the list.

For example, the following code initializes the list and then adds three email addresses to the list:

c.EmailAddresses = New List(Of String)
c.EmailAddresses.Add("bilbo@hobbiton.me")
c.EmailAddresses.Add("bilbo@yahoo.com")
c.EmailAddresses.Add("bilbo@live.com")

Using the collection initializers feature in VB 10, the code is as follows:

c.EmailAddresses = New List(Of String) From
               {"bilbo@hobbiton.me",
                "bilbo@yahoo.com",
                "bilbo@live.com"}

The collection initializer passes each value in the bracketed list to the collection’s Add method, thereby providing the same functionality as the prior example.

It may not look like you are saving much typing in this simple example. Collection initializers are even more useful if you need to populate lists of objects in code (e.g., testing, prototyping, or internal values).

You can see in this example a student class which leverages the new auto-implemented properties:

Public Class Student
    
    Public Property IsDirty As Boolean
    Public Property LastName As String
    Public Property StudentId As Integer
    Public Property Scores As List(Of Integer)
    
End Class

Using collection initializers, you populate this class as follows:

Dim students = new List(Of Student) From
        {New Student With {
            .LastName = "Baggins",
            .Scores = New List(Of Integer) From
                      {97, 92, 65, 88, 94}},
         New Student With {
            .LastName = "Cotton",
            .Scores = New List(Of Integer) From
                      {92, 92, 90, 100, 94}},
         New Student With {
            .LastName = "Brandybuck",
            .Scores = New List(Of Integer) From
                      {87, 72, 65, 88, 86}}}

Compare that to the code you have to write without collection initializers (Listing 3).

You can combine the use of collection initializers and auto-implemented properties to define a set of values for the property of a class:

Public Property StatusCodes As New List(Of String)
           From {"Active", "InActive", "Deleted"}

This code results in a property that represents a list of strings as defined in the bracketed list.

This technique is useful for any lists you define in code, such as lists of menu options. It works with the generic List, the generic Dictionary, and any other class that implements IEnumerable(Of T) and supports an Add method.

Better Support for Lambdas

VB 9 and .NET 3.5 support Language Integrated Query (LINQ) and lambda expressions. However, there were several features of lambda expressions that were not fully implemented until VB 10: action queries and multi-line lambdas.

Action queries perform an action with a minimal amount of code. For example, instead of having to type three lines of code:

For Each s As Student In students
    Debug.WriteLine(s.LastName)
Next

You can instead write it as follows:

students.ForEach(
          sub(s) Debug.WriteLine(s.LastName))

Multi-line lambdas are useful when you need to do additional work inside a lambda expression or when you need to debug a lambda expression.

Dim hasChanges As Boolean =
  students.Any(Function(s)
              If s.IsDirty Then
                  Debug.WriteLine(c.CustomerId);
                  Return true
              Else
                  Return false;
              End If
               End Function)

Notice the Return statements. In a single-line lambda, the return is implied. With multi-line lambdas, you need to add the return statements as appropriate.

Conclusion

This article covered many of new features in VB 10. Be sure to try them out!