BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Collection and Array Initializers in VB 10

Collection and Array Initializers in VB 10

This item in japanese

Bookmarks

Visual Basic 10, to be released with .NET 4.0 and Visual Studio 10, is adding support for collection and array initializers. While these are similar to what we already have in C#, there are minor enhancements such as support for extension methods and improved type inference.

Collection Initializers

Like C#, Visual Basic’s collection initializer works on classes that implement IEnumerable and expose an Add method. But unlike C#, the Add method may be defined in an extension method. The syntax looks like C# as well, but with the addition of the “From” keyword.

var x As new List<String>() {"Item1", "Item2"}

Dim x As New List(Of String) From {"Item1", "Item2"}

Passing in multiple parameters to the Add method is also quite similar.

var x = new Dictionary<int, string>(){{1, "Item1"}, {2, "Item2"}}

Dim x As New Dictionary(Of Integer, String) From {{1, "Item1"}, {2, "Item2"}}

In C# there is a slight ambiguity in the syntax, which makes it impossible to combine property initializers with object initializers. By using the keywords “With” and “From”, one might assume that VB could overcome this limitation and combine the two in a single statement. Unfortunately that isn’t the case and the following syntax is not allowed.

Dim x as New List(Of Integer) With {.Capacity = 10} From {1,2,3}

Another way VB is following C# is how exceptions are handled. If there is an exception when adding any item to the collection, the whole operation is aborted and the collection variable is left unchanged.

Array Initializers

Array initializers now support type inference, significantly reducing the amount of code that needs to be typed. As you can see below, the presence of the array contents in brackets is enough to both infer that an array is being created and what type that would be.

Dim x = {1, 2, 3}

In contrast, previous versions of VB required empty parens to signify an array. Also, it would define the variable as an object array unless otherwise indicated.

Dim x As Integer() = {1, 2, 3} ‘integer array

Dim x() = {1, 2, 3} ‘object array

Both multi-dimensional and jagged arrays are supported, though the latter has some somewhat clumsy syntax involving wrapping parentheses around each array.

Dim multi = {{1, 2}, {3, 4}}

Dim jagged()() = {({1, 2}), ({3, 4, 5})}

Array initializers may also be used inline for calling functions.

Rate this Article

Adoption
Style

BT