Array Literals

Visual Basic 2010 introduces a new feature known as array literals. Basically it works like the local type inference but it is specific to arrays. For example, consider this array of strings declaration as you would write it in Visual Basic 2008:

Dim anArrayOfStrings() As String = {"One", "Two", "Three"}

Now in Visual Basic 2010 you can simply write it as follows:

'The compiler infers String()
Dim anArrayOfStrings = {"One", "Two", "Three"}

According to the preceding code, you are still required to only place a couple of parentheses, but you can omit the type that is correctly inferred by the compiler as you can easily verify by passing the mouse pointer over the variable declaration. Of course, array literals work also with value types, as shown here:

image

Array literals also support mixed arrays. For example, the following array is inferred as an array of Object:

'Does not work with Option Strict On
Dim mixedArray = {1.23, "One point Twentythree"}

The preceding code will not be compiled if Option Strict is On and the compiler will show a message saying that the type cannot be inferred, which is a situation that can be resolved explicitly by assigning the type to the array. You could therefore explicitly declare the array as Dim mixedArray() As Object but you need to be careful in this because mixed arrays could lead to errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.53.166