Monday 10 February 2014

New features in VB.NET 11 (.NET 4.5)

Unlike the release of VB.NET with .NET 4.0, the next release of VB.NET doesn’t have the anything like as many new features, which is almost certainly because the language is really maturing and a lot more parity has been achieved between C# and VB.NET.

Async

The big new feature for both languages is the introduction of the await/async keywords. I won’t go into detail here because they are covered in lots of other places (including the VB.NET team blog).

Yield

One if the freebees we get because of the Async feature is the Yield keyword. This has been a feature of C# for a long time, and although not massively useful, when you do need it, it can save you a lot of time. Let look at an example.

Imagine you have a function that takes an array of integers and returns an IEnumerable(Of Integer) containing the even numbers in that array (I know – completely contrived demo). The easiest way to do it would be to build a list and then return it once it is complete, for example:

Function GetEvens(numbers As Integer()) As IEnumberable(Of Integer) 
  Dim evenNumbers As New List(Of Integer)
  For Each number in numbers
    If number Mod 2 = 0 Then
      evenNumbers.Add(number)
    End If
  Next
  Return evenNumbers
End Function

With the Yield keyword we no longer need the List to hold the results, we can return them (yield them) as we find them, making our function look like this:

Function GetEvens(numbers As Integer()) As IEnumberable(Of Integer)
  For Each number in numbers
    If number Mod 2 = 0 Then
      Yield number
    End If
  Next
End Function

Global

The Global keyword has existed for a while to allow you to be explicit about which namespace you want. For example, assume you have this namespace in your project:

Namespace Acme.System.IO

If you have Imported the Acme namespace this line becomes ambiguous:

Dim dataFile As System.IO.File

The global keyword allows us to be explicit:

Dim dataFile As Global.System.IO.File

In the next version of VB.NET we will also be able to use the Global keyword in namespace declarations (for exactly the same purpose). Kind of minor, but useful when you need it.

0 comments:

Post a Comment