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)

0

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

4 Comments

...and it's zero-based so you have elements at indices 0 and 1 -- thus length = 2.
Thanks alot, added this to my "Why I dislike VB.NET" checklist!
One option is to avoid arrays entirely. blogs.msdn.com/ericlippert/archive/2008/09/22/…
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.