I ran into a recent issue today relating to array declarations in VB.Net. I looked up array declarations on the net and found something that gave me hope, but alas…
In VB6 declaring an arrayDim Items(5) As String
gives you 6 items from index 0 to index 5. In VB.NET, this same declaration will yield 5 elements from index 0 through index 4. Be on the look out for “out of bounds” type errors. Also, all arrays in .NET must now be zero-based.”
My personal favorite is the last line. He says it like it’s a bad thing! In any case, I didn’t include the source of the quote because the guys is wrong (or at least no longer correct for all versions after .Net beta1, I believe). True, all arrays in VB.Net must now be zero-based, and thank the computing gods for that, but for the sake of backwards compatibility VB.Net still supports the good(bad)-ole-way of declaring arrays.
Coming from C# (and C and Java…) this was a bit of a surprise. In particular because I have the habit of declaring know max sizes for arrays as constants. If I was only a VB programmer this wouldn’t be so annoying, but it is. Also, handy little tools like Convert.Net don’t handle this case at all, so if you used it to convert C# snippets to VB you would be serving yourself up an instant logical error. Those Visual Fred guys, always trying to be different…
So, “Dim Items(UpperBound) as String” is just the way things work, I’ll just have to accept it. Thank God for TDD, that’s all I have to say. If I wrote a bunch of code on my previous assumptions without coverage I would have hated life ferreting out all the places that I would have made the same mistake. I know that this is the way VB6 worked, but again, I thought that VB6 was pretty stupid when it came to arrays.
It’s kind of sad though, why can’t the VB folks conform a little to the masses?
I.E. Here are some other languages declaring arrays containing 10 elements (My COBOL is way weak, so excuse any syntax errors):
int myArray = new int;
int myArray = new int;
myArray = Array.new(10)
05 ARRAY-VALUES PIC9(3) OCCURS 10 TIMES
DIMENSION myArray(10) ! Although arrays can also be defined with upper AND lower bounds similar to VB6
(setq myArray (make-array 10 :element-type ‘integer))
Post Footer automatically generated by Add Post Footer Plugin for wordpress.