tags:

views:

3599

answers:

4

I've tried this code in VB:

Dim a(1) As Byte
Console.WriteLine(a.Length)

The output is "2". Anyone any idea why?

+2  A: 

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.

SMB
+2  A: 

Dimension Length The index of each dimension is 0-based, which means it ranges from 0 through its upper bound. Therefore, the length of a given dimension is greater by 1 than the declared upper bound for that dimension.

Array Size in Visual Basic

Nescio
+4  A: 

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)

AlexDrenea
+2  A: 

VB.NET:

 Dim a(1) as Byte ' under the hood, translated to byte[2] 
 Console.WriteLine("{0}", a.Length) ' output 2

 a(a.Length) = 7  ' no error

C#:

 byte[] a = new byte[1];
 Console.WriteLine("{0}", a.Length); // output 1

 a[a.Length] = 7; // error: Index was outside the bounds of the array.

The reason why Microsoft designed VB.NET to pad an extra element is, some companies want their legacy VB6 programs ported to .NET, using VB.NET. VB6 array default initial index is 1, unless you declare Option Base 0. To ease migration process for those VB6 data structure(arrays that starts with 1), they pad an extra element for VB.NET array declaration. So even old VB(6) can be ported directly to VB.NET (e.g. VB6's: For I = 1 To UBound(a))

VB.NET:
MessageBox.Show(a.GetUpperBound(0).ToString() & " " & a.Length.ToString()) ' outputs 1 2

C# doesn't need to pad an extra element, nor need GetUpperBound . It doesn't have VB's old cruft (array that starts at index 1, instead of 0). VB.NET array has one wasted memory so it can support old VB array idiom(array that starts at 1)

Michael Buen