tags:

views:

203

answers:

2

Coming from a C# background, I have no idea why the following declarationr returns an array with length = 2, can someone please enlighten me?

Dim lTestArray(1) As String

Console.WriteLine(lTestArray.Length) (writes 2)

+3  A: 

VB.NET array declarations supply the upper bounds (i.e. the maximum index) of the array, not the length. Since arrays are 0-based, a maximum index of 1 gives you two elements (0 and 1).

Adam Robinson
...and it's zero-based so you have elements at indices 0 and 1 -- thus length = 2.
tvanfosson
Thanks alot, added this to my "Why I dislike VB.NET" checklist!
Dominiek
One option is to avoid arrays entirely. http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
Adam Robinson
@Adam: another option is not to dimension the arrays like this in the declaration, and instead using either `Array.Resize` or the C#-like `New` syntax for arrays.
Konrad Rudolph
+1  A: 

In VB.NET, you don't specify the length of the array... you actually specify the index of the last addressable element. Since .NET arrays are 0 based, and you specified 1 to be the last indexable element, the length is 2.

Nick