Thursday, January 27, 2011

VB arrays vs. C# arrays in ASP.Net

As many long-time web developers may know, Visual Basic and VB Script used to have 1-based arrays for many years while just about every other language I used -- C, C++, JScript, JavaScript -- had 0-based arrays.  I didn't particularly have any strong preference for one over the other, but it was tricky to adjust your mind when switching from one to the other.

Then when .Net was released, Visual Basic changed to using 0-based arrays.  And with ASP.Net, Microsoft switched from using VBScript to using Visual Basic.  So now the two main languages used by ASP.Net, C# and Visual Basic, both use 0-based arrays.  That's good news in the long run, but I'm sure it caused a lot of developers some big migration headaches.  But there is still one annoying difference in the arrays of these languages that caused me some problems in a current ASP.Net application that is using VB.

The meaning of the boundary specified when you declare a fixed size array in C# versus VB is different.  When you declare a fixed size C# array with a boundary of 10, such as:

int[] myArray= new int[10];

then the array has 10 elements, which is what I would expect.  Since the array is 0-based, the elements are indexed as myArray[0] through myArray[9]

When you declare a fixed size VB array with a boundary of 10, such as

Dim myArray(10) as Integer

then 10 is the index of the last element.  So the array actually has 11 elements in it, indexed as myArray(0) through myArray(10)!  To me, this is very misleading.  So I thought I was filling my array up, but really I had a blank element at the 10th index that was causing problems.

For a more extensive comparison of VB and C# arrays using code examples, see the array section of this VB.NET and C# comparison.