tags:

views:

36

answers:

4

Hi, I have an array variable (string type). It contains certain no. of items, that I donot know how many they are. I need to run a loop for that many nos. that the array contains. I tried LBound and UBound loop but it says my array is not a system array. How can I know how many items my array contains?

Thanks Furqan

+3  A: 

You can use the Length property of the array object.

From MSDN (Array.Length Property):

Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.

Read about arrays in VB.NET and the Array class for better understanding of arrays in VB.NET and the .NET framework.


Update:

However, for looping over an array you should simply use a For Each loop (as an array is treated like any other collection in .NET) - this way you will not make any silly mistakes with array bounds and off by ones:

For Each item As arrayItemType in MyArray
  ' do stuff with item
Next

See the example on this page.

Oded
+1  A: 

You look at the length:

To get the number of items in the first dimension: arrayName.GetLength(0)

If you need the index, use GetUpperBound(0)

Some helpful examples here.

DOK
A: 

If the compiler is telling you that your variable is not a system array, then chances are, it's not an array. If it's not an array, you won't be able to get its bounds through any means.

Inspect the variable in the locals window and verify that your variable is of the type that you think it is. It's probably not an array after all.

Mike Hofer
+1  A: 

Like Oded said, you can use the Length-propery of the Array. This would look something like this:

    Dim data As String() = {"one", "two", "three", "four"}

    For i = 0 To data.Length - 1

        Console.WriteLine(data(i))

    Next

If you just want to loop all strings in your array, you can use For Each as well:

    For Each s As String In data

        Console.WriteLine(s)

    Next
Dave
+1 for suggesting `For Each`
Oded