Size of array in Visual Basic? Size of array in Visual Basic? arrays arrays

Size of array in Visual Basic?


If you are used to C/C++/C# languages you are used that when declaring an array to initialize it with the number of elements in the array.

C# : byte a[] = new byte[1]

will declare a byte array with 1 element (upperBound = 0)

The behavior is different in VB where, when declaring an array the parameter used in initialization represents the UpperBound of the array.

VB.NET: Dim a(1) As Byte

will declare a byte array with 2 elements (upperBound = 1)


In Visual Basic, the size of an array is declared with the array's upper bound, where most languages declare the size of an array by specifying the number of elements in the array. If you aren't aware of this, then your Visual Basic arrays end up being 1 element longer than you expected:

VB.NET:

 Dim a(1) as Byte ' under the hood, translated to byte[2]  Console.WriteLine("{0}", a.Length) ' output 2 a(0) = 7 ' No error, element exists a(1) = 7 ' No error, element exists, array length is 2 a(a.Length) = 7  ' error: Index was outside the bounds of the array.

C#:

 byte[] a = new byte[1]; Console.WriteLine("{0}", a.Length); // output 1 a[0] = 7 // No error, element exists a[1] = 7 // error:  Index was outside of bounds of the array. (because array length is 1) a[a.Length] = 7; // error: Index was outside the bounds of the array.

The reason why Microsoft designed VB.NET to size arrays based on upper bound rather than array length is to make it easier to port code from VB6 to VB.NET. The initial index of a VB6 array is 1, unless you declare Option Base 0. It was common to loop through an array of size N using For i = 1 To N. By designing VB.NET to interpret an array's sizing argument as an upper bound rather than the number of elements in the array, old VB6 code that looped from 1 to N could be ported directly to VB.NET. The array in VB.NET will have one extra element compared to what the array had in VB6 (the element at index 0) but otherwise behaves as it did in VB6.

You'll sometimes see people claim that Visual Basic creates a "wasted" element. This is only true when porting legacy VB6 code which didn't expect an element at index 0. When writing new code, you just have to remember what the sizing parameter means (upper bound, not element count), and declare your arrays accordingly. Just reduce your sizing parameters by one compared to what you'd see in C#. The resulting array will have elements from a(0) to a(a.Length-1), just like a C# array.


Array starts from position 0. You are defining two positions.

If you want only 1 position, then:

Dim a(0) As Byte

and you will get a.Length as 1.