Visual Basic 11 Beta Available for Download!

Visual Basic 11 Beta Available for Download!

Rate This
  • Comments 17

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

Leave a Comment
  • Please add 7 and 1 and type the answer here:
  • Post
  • I'm not sure if the await example makes sense: TextBlock1.Text is set *after* the await line, which means it is part of the continuation. Thus, "Retrieving File..." is printed only *after* the file has been downloaded completely...

  • Why the new Iterator keyword? is it because you found a lot of/important customers with problems because they used "yield" as a variable name in their codebases? Or is it because of something else?

    Are the arguments decorated with the new Caller Info attributes visible to developers? or only inside the scope of the method? It would be nice if it would be the second.

    PS: Sorry if this appears as a double comment, I don't know if my previous one has been submitted.

  • Good going.  Delegates and background threads finally simplified.

    Add in a WPF databinding check method like BOOL Me.Property.EnsuredIsBoundToXaml() and we're set

  • @Heinzi - good catch!  We've updated the code sample

  • Héctor,

    While the Iterator keyword definitely allowed us to avoid the problem you mention of introducing a breaking change to existing source bases which use Yield as an identifier (e.g. financial applications) and to keep a concise keyword like Yield instead of a keyword pair such as Yield Return that wasn't the only reason. VB, in general has a declarative style to it (XML literals, Handles, Implements); we felt that it was important in VB that if a function was an iterator that the code simply state that. Similarly if people were going to call them Iterator and Async Functions then the code should as well. You can see this pattern in other VB modifiers such as ReadOnly and WriteOnly properties - we could infer that the Setter was missing but semantically that means ReadOnly so the property is declared ReadOnly.

    Another benefit to the explicit declarative modifier is that we can give a better editor experience. In VB when you type "Iterator Function F As Integer" the IDE will automatically insert the "IEnumerable(Of Integer)" for you. Similarly if you type "Async Function F As Integer" the IDE will replace the "As Integer" with "As Task(Of Integer)" so that you don't have to. Again, parallels can be drawn with Properties where the presence of the ReadOnly modifier allows us to auto-generate better code for you.

    As for the CallerInfo attributes they don't hide the parameters from consumers of the method, no. These parameters look just like normal optional parameters. This is important as an example for a method which has multiple overloads which take CallerInfo parameters. One overload should explicitly pass its arguments to other overloads to preserve the line CallerInfo of an external caller. Otherwise the innermost overload would always get the CallerInfo of whatever other Overload called it. We're looking at ways to note these parameters as more special though such as displaying "(caller name)" or the current line number as the default value instead of the one declared in source to make it clearer to developers their true nature.

    Regards,

    Anthony D. Green

    Program Manager

    Visual Basic & C# Languages Team

  • I would like to see nested subprocedures.  A sub or function that is declared completely within the context of another sub and could only be called from within that parent sub.  The parent sub's variables would be available to the child.  There are so many times when I want to call a new sub that will only be called from one sub and I have to pass lots of parms to the new sub.  Nested subs would allow me to write the new sub inside the parent without having to pass parms.  Delphi has had this for years!

  • I would like to get notes about the classes in VB.net. I am still new in programming. I can be contacted at tshepomiya@gmail.com

  • I would like to see nested subprocedures ! (Me to!)

    @JC: Delphi is a real-oop language....

    Class Test

     Public Sub New()

     End Sub

     Public Sub New(Param as string)

      .......

     End Sub

    End class

    Class NotOOP

     inherits Test

     Public Sub New()

     End Sub

    End class

    So: Bla as new NotOOP("Delphi is for nerds, VB is just what it is..... Basic stuff")

  • Jeg har besvær med at Downloade Visual Basic 11 Beta.

  • Although declarative style is often nice, it may also make the language a bit more verbose, which is a problem for some people out there.

    Also, on the subject of properties, when you make an interface with a readonly property, C# allows its implementation to have a private set, however in VB you are forced to use ReadOnly, which may be correct at some levels, but on others it makes you add some more code than desired. I hope this won't cause similar undesired behaviour.

  • The Real Transparency and Opacy, on controls, stills not be possible?

  • How about making Option Strict On as default? I'm sure that would please many dedicated VB programmers as well as myself. And as Joaquim mentioned, Opacity property on controls would be very nice.

  • Opacity on controls is a Windows Forms issue, and it's unlikely we'll see any new update for it ever... a shame, because I still prefer Windows Forms over WPF when making a desktop app, but if it was already placed aside by Microsoft when WPF made its debut, now with Metro we can completely forget about it.

  • sorry, but what is the language limitation!?! is our imagination;)(is what everyone learn)

    then why not, just, update the Transparency property(make it more faster) and with these way we can do the Opacy too(they continue be a false Transparency\Opacy, but better use it more faster than nothing);)

  • @JC "I would like to see nested subprocedures. .."

    You can already do that; I do it all the time:

    public sub foo()

      dim innerSub = sub()

                                   doSomeStuff()

                              end sub

      innerSub()

    end sub

Page 1 of 2 (17 items) 12