Wriju's BLOG

.NET, Cloud and everything

VB.NET 10 : Working with Array

Working with Array in VB.NET 2010 (VS 2010) is real fun. You can leave it to the compiler to decide. Be it one dimensional array, two dimensional array or jagged array..

One-dimensional Array

When you declare something

Dim arr() As Integer = New Integer() {1, 2, 3, 4}

You explicitly mention the type so on. Fairly simple.

But when you mention an array with

Dim arr() = {1, 2, 3, 4} if it contains same type will create an array of that type. In this case Integer array.  


But if you declare an array like

Dim arr()  = {1, 2, 3, 4.0} it then creates the array as Double as it is widest type and all the integers can be converted to Double. But when you declare with string as one of elements


Dim arr = {1, 2, 3, 4.0, “5”}


This will create an array of Object as converting an integer from string and converting a string from integer is narrowing conversion. So this will actually create


Dim arr() As Object = {1, 2, 3, 4.0, “5”} and  hold the actual type like ArrayList


Matrix Array


If you want to declare an array like

Dim arr1 = {{1, 2}, {3, 4}}             ‘ arr1(,) Integer

Dim arr2 = {{1, 2, 3}, {3, 4, 5.0}}     ‘ arr1(,) Double


Jagged (Array of Arrays) Array

If you want to create jagged array but try with the below code

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

The compiler will throw you an error assuming that you might have some mistake. So to be explicit you can declare it

Dim arr2 = {({1, 2, 3}), ({3, 4})}