Array Literals in Visual Basic 10/VS 2010
Posted: April 8th, 2010 | Author: Michael | Filed under: .NET | No Comments »Prior to Visual Basic 10 the type and dimension of an array was required when declaring it. Visual Basic 10 introduces array literals in which the compiler infers the type and dimensionality based on the values you use to initialize the array. The compiler can handle some data type mismatches; however, it does not handle them all. Notice the forthArray. This array contains integers and strings. The compiler creates an array of type object. Also notice that in the last example the compiler knows to create a two dimensional, integer array.
Sub Main()
Dim firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}Console.WriteLine("First Array Type: " & firstArray.GetType().ToString())Dim secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9.9}
Console.WriteLine("Second Array Type: " & secondArray.GetType().ToString())
Dim thirdArray = {"One", "Two", "Three", "Four"}
Console.WriteLine("Third Array Type: " & thirdArray.GetType().ToString())
Dim fourthArray = {"One", 2, "Three", 4}
Console.WriteLine("Forth Array Type: " & fourthArray.GetType().ToString())
Dim multiDimArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Console.WriteLine("Two Dimensional Array Type: " & multiDimArray.GetType().ToString())
Console.ReadLine()
End Sub
Sub Main() Dim firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}Console.WriteLine("First Array Type: " & firstArray.GetType().ToString())Dim secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9.9} Console.WriteLine("Second Array Type: " & secondArray.GetType().ToString()) Dim thirdArray = {"One", "Two", "Three", "Four"} Console.WriteLine("Third Array Type: " & thirdArray.GetType().ToString()) Dim fourthArray = {"One", 2, "Three", 4} Console.WriteLine("Forth Array Type: " & fourthArray.GetType().ToString()) Dim multiDimArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Console.WriteLine("Two Dimensional Array Type: " & multiDimArray.GetType().ToString()) Console.ReadLine() End Sub
Output from running the above code:
First Array Type: System.Int32[]
Second Array Type: System.Double[]
Third Array Type: System.String[]
Forth Array Type: System.Object[]
Two Dimensional Array Type: System.Int32[,]










Leave a Reply