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
... 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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
ver 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):
So, the property you want to iterate over needs to be:
Dim fols as New List (of clsFolders)
I assume you have a class grouping folders together because you want to add other properties/functions/whateDim fols as New List(of clsFolder)
For Each folder as clsFolder in fols
' Actionable code
Next
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
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.