views:

48

answers:

2

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

+1  A: 

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)

bobbymcr
Bobby please see Jeremy's answer. Yours and his are in conflict
hamlin11
Everything I said is correct. In the statement `For Each o As MyObject in MyArray`: (a) `MyArray` must implement `IEnumerable`; if not, you'll get a compile error. (b) the types that are contained in `MyArray` must be convertible to `MyObject`; if not, you'll get a runtime error.
bobbymcr
Yes, Bobby's right. In .NET arrays implement IEnumerable, and if you declare MyArray As MyObject then the cast to MyObject isn't required.
Jeremy McGee
+1  A: 

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.

Jeremy McGee
Since it internally has the array implement IEnumerable, do I need to do anything special to my class such as overload certain operators?
hamlin11
You don't need to add anything to your MyObject class to allow MyArray to contain it as an IEnumerable collection. IEnumerable is quite simple: it contains methods MoveNext, Reset and a property Current. MSDN has an example at http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx.
Jeremy McGee