Link to home
Start Free TrialLog in
Avatar of jjsather
jjsather

asked on

How to create VB.NET classes that enable For Each loops?

With code like the below...

    
Public Class clsFolder
    Public Name As String
    Public Size as Integer
End Class
Public Class clsFolders
    Dim oFolders As New List(Of clsFolder)
End Class

Open in new window

... how can I enable "For Each" enumeration over a variable declared as clsFolders with code like below? I've read about IEnumerable, which I assume is needed here, but I'm not tracking and any syntax I've attempted is incorrect.

Dim fols As New clsFolders
For Each fol As clsFolder In fols
    ' Gives compile error on "fols" above
Next

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

You can only For Each over something that implements IEnumerable. Within your clsFolders class you have something that implements IEnumerable:  oFolders. Loop over that:

Dim fols As New clsFolders
For Each fol As clsFolder In fols.oFolders
    ' do something
Next

Open in new window


Off-topic:

[1] Hungarian notation (e.g. clsXXXX) is not a recommended practice in .NET code. Just name your class "Folders" and be done with it.

[2] VB.NET is a case-insensitive language, but the commonly-accepted standard is to capitalize type names (i.e. class names). The same goes for property names in your classes.
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think you might be over-thinking this one. You simply need to make the property you want to iterate over be a collection type OR a generic collection of said type. In today's world the latter is the preferred, best practice way because it simplifies things immensely while providing all the functionality you're looking for.

So, the property you want to iterate over needs to be:
Dim fols as New List (of clsFolders)

Open in new window

I assume you have a class grouping folders together because you want to add other properties/functions/whatever to that class in addition to the collection of folders that is already there. If that was not your intent, then you only need to do the following (as @käµfm³d has already implied):
Dim fols as New List(of clsFolder)

For Each folder as clsFolder in fols
    ' Actionable code
Next  

Open in new window

Avatar of jjsather
jjsather

ASKER

Just doing Inherits is all I ultimately needed. Thanks...

Public Class clsFolder
    Public Name As String
    Public Size as Integer
End Class
Public Class clsFolders
    Inherits List(Of clsFolder)
    Public Sub New()
        MyBase.New()
    End Sub
End Class

Open in new window