Visual Basic 11 Beta Available for Download!

As you may have read in Jason’s announcement, today we announced that Visual Studio 11 Beta is now available for download.  This is a huge release for Visual Basic as it provides full platform support for building Windows 8 Metro style apps, a first-class asynchronous programming experience, and also the long-awaited Iterators feature.  And in the true spirit of VB, you’ll see a ton of other improvements that will make you more productive every day.

 

Async
As the world moves to mobile phones and tablets, the demand for responsiveness in today’s applications is higher than ever.  Things like database queries, network requests, and disk access all have potential to block the UI and leave users frustrated.  While user expectations continue to climb, the tool/platform support for making asynchronous programming easy hasn’t kept pace, until now.  With the new Async/Await keywords, VB11 makes asynchronous programming really simple: 

   Public Async Function GetStorageFile() As Task(Of Windows.Storage.StorageFile)

 

        Dim packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation

 

        TextBlock1.Text = “Retrieving File…”

        Dim packagedFile = Await packageFolder.GetFileAsync(“FileLocatedInPackage”)

        ...

        Return packagedFile

    End Function

 

The Await keyword kicks off an asynchronous request without blocking the UI.  The function returns a Task(Of T) at the point of the Await expression, but this is just a placeholder for the return value that will come from GetFileAsync.  Once that work completes, the method resumes and the variable packagedFile is assigned to. 

Be sure to check out the Asynchronous Programming Developer Center for articles, videos, and samples on how to use Async.  This blog post has a good conceptual explanation of async, and Lucian’s blog has a ton of great resources for learning the feature. 

VB11 also includes full async debugging support.  F10-Step-Over (or Shift+F8 on VB Profile) now does what you’d expect.  If you’re still on the function-declaration-line then it steps out to the caller. But often (e.g. if you’ve gone past an await) then the concept of “caller” doesn’t even exist. So, for consistency, if you’re anywhere outside the declaration line then Shift+F11 (Ctrl+Shift+F8 on VB Profile) will step out to someone who’s awaiting you. 

The other thing we’ve added is async unit-testing support in MSTest.  xUnit now supports this as well.

 

    <TestMethod>

    Async Function Test1() As Task

        Dim x = Await Engine.GetSevenAsync()

        Assert.AreEqual(x, 6)

    End Function

 

    <Xunit.Fact>

    Async Function Test2() As Task

        Dim x = Await Engine.GetSevenAsync()

        Xunit.Assert.Equal(x, 6)

    End Function

 

 

Iterators
Iterators are a new feature in VB11 that make it easier to walk through collections such as lists and arrays.  Each element is returned to the calling method immediately, before the next element in the sequence is accessed. 

 In addition to working with collections, you can use iterators to write your own custom LINQ query operators.  For instance, the following example prints out only the even numbers in the array: 

Module Module1

 

    Sub Main()

 

        Dim query = From n In {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

                    Where n Mod 2 = 0

                    Select n

 

        For Each item In query

            Console.WriteLine(item)

        Next

 

        Console.ReadLine()

 

    End Sub

 

    <System.Runtime.CompilerServices.Extension>

    Iterator Function Where(source As Integer(),

                            predicate As Func(Of Integer, Boolean)

                           ) As IEnumerable(Of Integer)

 

        For Each num In source

 

            If predicate(num) Then

 

                Console.WriteLine(“Yielding “ & num)

                Yield num

 

            End If

        Next

 

    End Function

 

End Module

 

Note the new Iterator and Yield keywords in the Where function.  (The LINQ query binds to this Where extension method since it’s a better match than the Where(Of T) operator defined in the standard query operators).

 VB also allows iterator lambdas!  In this example, we use an iterator in an expression context and combine it in a powerful way with XML Literals (note that we’re effectively embedding statements inside embedded expressions now):

 

        Dim images =

            <html>

                <body>

                    <%=

                        Iterator Function()

 

                            For Each fn In IO.Directory.EnumerateFiles(“c:\\”, “*.jpg”)

                                Yield <img src=<%= fn %>></img>

                            Next

                        End Function.Invoke() %>

                </body>

            </html>

 

Namespace Global
VB has always had the Namespace and Global keywords, but now you can use them together!

 

Namespace Global

Namespace Global.<NamespaceName>

 

This gives you a lot more flexibility around which namespace your code ends up in, and is particularly useful for code-generation scenarios.  For a full description of the feature, check out Lucian’s excellent post here

Optional Parameters in Overloaded Methods
Previously, overloads of a method were not permitted if the only difference between them was optional parameters, so the following code would be invalid:

    Sub f(x As Integer)

    End Sub

 

    Sub f(x As Integer, Optional y As Integer = 0)

    End Sub

 

In VB11 this code is now valid, which gives you more flexibility and improves the ability to version methods (though there’s still more we need to do in this area).

 

Limitless (Command-line) Errors!
This is actually a good thing, let me explain.  For performance reasons, the Visual Basic IDE maxes out at 101 errors (with error #102 being “Maximum number of errors exceeded.”)  This can make it difficult to estimate the amount of work remaining in certain situations, particularly in upgrade scenarios.  We have removed this limit from the command-line compiler in this release, though it still there in the IDE.  What this means is if you want to know exactly how many errors there are for a project, just invoke the compiler through msbuild.exe or vbc.exe and you’ll get your answer.

Caller Info Attributes
The compiler now recognizes three special attributes: <CallerMemberName>, <CallerLineNumber>, and <CallerFilePath>.  This is great for logging scenarios, and allows you to have the name, line number, and/or file path of the invoking method passed into the logging function as optional parameters. 

Another great use case for this is when implementing INotifyPropertyChanging:

 

    Class C

        Implements INotifyPropertyChanged

 

        Dim backing As New Dictionary(Of String, Object)

 

        Property p As String

            Get

                Return GetProp(Of String)()

            End Get

            Set(ByVal value As String)

                SetProp(value)

            End Set

        End Property

 

        Public Function GetProp(Of T)(<CallerMemberName()> Optional prop As String = Nothing) As T

            Debug.Assert(prop IsNot Nothing)

 

            Try

                Return CType(backing(prop), T)

            Catch ex As KeyNotFoundException

                Return CType(Nothing, T)

            End Try

        End Function

 

        Public Sub SetProp(Of T As IComparable(Of T))(value As T,

           <CallerMemberName()> Optional prop As String = Nothing)

 

            Try

                Dim oldvalue = CType(backing(prop), T)

                If value.CompareTo(oldvalue) = 0 Then Return

            Catch ex As KeyNotFoundException

            End Try

 

            backing(prop) = value

            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(prop))

        End Sub

 

        Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

 

    End Class

  

Simplified Code Spit (a.k.a. No More ByVal!)
The IDE will no longer insert “ByVal” in method signatures unless you explicitly type it in.  This reduces a lot of the visual noise in method declarations and makes them more readable.  Also, the IDE will no longer insert the fully-qualified name for a type (such as “System.Object” or “System.EventArgs”) when the applicable imports are already in scope.  (Because in this case “System” is already a project-level import).

VB10:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

 

VB11:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

 

This also works automatically for all interface methods generated when you press enter after an Implements clause.

 

View Call Hierarchy
In VB11, if you right-click a method name, you’ll see a new option for “View Call Hierarchy” that brings up a window that looks like this: 

 
(Click on the image to see a more detailed view)
 

It shows you all calls to/from that method, and also if it gets overridden anywhere.  You can then walk the tree and understand how these methods are used throughout your codebase.  For a more detailed overview, check out this post.

 

Getting Started
Hopefully that gives you a taste of what’s new in VB11 (and we haven’t even touched on all the performance improvements!).  There are far more enhancements than we can cover here, so watch for a future post that goes into more detail.  For next steps:

 

1.       Download the Bits!
Download Visual Studio 11 Beta (you can also get Team Foundation Server 11 Beta, and .NET Framework 4.5 Beta from here).  Visual Studio 11 Beta can be installed on Windows 7, or you can install it on top of the Windows 8 Consumer Preview.

 

2.       Learn More!
In addition to Jason’s post, Jason’s announcement, be sure to check out the new Windows 8 app developer blog for a list of great improvements across Visual Studio.  For Samples, check out the Windows 8 Sample Gallery. To explore what’s new in Windows 8, check out the Building Windows 8 blog post announcing the Windows 8 Customer Preview.

 

3.       Send us Feedback!
The forums are available for questions, both in Visual Studio and Windows 8.  If you find a bug please let us know through the Microsoft Connect site. For feature suggestions check out the UserVoice site (which also allows you to vote on other users’ feature ideas). 

 

We hope you enjoy the product and look forward to seeing tons of great VB apps!

Jon Aneja, Program Manager, VB/C# Compiler Team
Lucian Wischik, Program Manager, VB Spec Lead