19

I'm reviewing an automatic translation of VB6 code to C# and the convertor translated someArray(3) to someArray[3]. But accordingly to the old code documentation it should pick the third element not the fourth as it is doing in the translated version.

Are array indexes 0-based in VB6? Or do they start at 1?

MarkJ
  • 29,252
  • 4
  • 60
  • 104
Jader Dias
  • 81,082
  • 147
  • 410
  • 611

2 Answers2

18

Yes - arrays are (generally) 0 based in VB6

The exceptions to this are when the explicit Dim someArray(1 To 10) as Int syntax has been used, or when Option Base 1 is declared at the top of the code module.

It's Collections that aren't - when you loop through Collection objects I'm pretty sure that they are 1 based.

Jon Egerton
  • 36,729
  • 11
  • 90
  • 125
  • 4
    "Unless Explicit Type Syntax has been used" *Or* `Option Base 1` has been declared at the top of the code block – Matt Wilko Jan 09 '12 at 11:47
  • @Matt Does this statement affect only the current file? – Jader Dias Jan 09 '12 at 11:52
  • @XMLforDummies: Yes - in VB6 you have the `Option` statements at the top of each code file. – Jon Egerton Jan 09 '12 at 11:53
  • @XMLforDummies - Yes, so if say you have two modules and ModuleA has Option Base 1 declared then any array declared in ModuleA is 1 based. – Matt Wilko Jan 09 '12 at 11:54
  • 1
    Unless explicitly specified otherwise at the moment of array declaration. It gets complicated. That's one of the reasons why they changed this for VB.NET. – Cody Gray Jan 09 '12 at 11:54
7

The short answer is that array lower bounds are what you tell them to be.

The default is base 0 (unless overridden by Option Base 1), but you can declare lower bound to any value you want (Dim arr(-42 To 42) is as valid as Dim(3)).

Also, if an array is returned by some object, its lower bound is whatever that object sets it to. For example an Excel Range.Value reference will return a 1 based array.

chris neilsen
  • 48,099
  • 10
  • 78
  • 115