Question

I'm using VS2008.

Is the following OK to do the following VB.NET with a very simple class (see below)?

for each CurrentObject as MyObject in MyArray
  'access current object
next

The "simple class":

Class MyObject
  public I as integer
end class

I seem to remember that something about needing iEnumerable, but my compiler isn't complaining.

Edit: Clarification

Was it helpful?

Solution

This is completely fine.

Internally, .NET has your array MyArray implement IEnumerable, which is what the compiler looks for and uses when you use a foreach loop of this kind.

So you don't need to do anything more.

Indeed, if MyArray is already declared as an array of MyObject you won't need the cast to MyObject, so

Dim MyArray(20) As MyObject
for each CurrentObject in MyArray  
    'access current object
next

will always work just fine as CurrentObject will always be of type MyObject.

You only need the cast if there's nothing to tell .NET what type your array contains.

OTHER TIPS

For Each only works for types which implement IEnumerable, generally collections. You should be aware that the item cast which happens for each element of the collection is done at runtime, though, so even though the code compiles, it may fail when executed.

You can read more about this on MSDN: For Each...Next Statement (Visual Basic)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top