0

I declare my array

Dim A(N) As Integer

When I loop from 1 To N or 0 To N-1 there's an extra value at one end or the other.

What's going on?

(Intended to be a canonical question/answer.)

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101

1 Answers1

0

In VB.NET arrays almost always* have a lower bound of 0 and are declared mentioning their upper bound, not their length.

They did change the VB.NET syntax early on to allow you to remind yourself if needed:

Dim A(0 To N) As Integer

That 0 can't be anything else (such as a 1 or a constant zero).

You can loop through all VB.NET array indexes using

For i = LBound(A) To UBound(A)

or, more simply,

For i = 0 To N

(*) You can use the .NET Framework to create arrays with other lower bounds, but you need to refer to them as Array and thus with late binding (and probably Option Strict Off).

Graham
  • 7,431
  • 18
  • 59
  • 84
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
  • 3
    It's not strictly true that arrays in VB.Net always have a lower bound of zero, see this overload of [`Array.CreateInstance`](https://msdn.microsoft.com/en-us/library/x836773a.aspx). It's just that anyone found writing such code should never be allowed near computers again. – Damien_The_Unbeliever Apr 24 '15 at 06:53