GetEnumerator. Some collections in .NET, such as the List, have a GetEnumerator function that can be used to access elements in a unified way. We can use GetEnumerator to get an Enumerator.
For most programs, we will want to just the List directory, and loop over its elements in a For-Each loop. But occasionally a more abstracted approach (like IEnumerator) is helpful.
Example. This program calls the GetEnumerator Function on a List of Integers. It shows how we can use GetEnumerator and then pass the Enumerator as an IEnumerator instance.
Part 1 We create an empty List Of Integers, and then in 3 subsequent calls to Add, we add 3 elements to the List.
Part 2 We call GetEnumerator. This returns a typed Enumerator, and we can pass this object as an IEnumerator (it implements IEnumerator).
Part 3 Once we have an IEnumerator reference, we can call MoveNext and Current to iterate over the elements in the underlying enumerator.
Module Module1
Sub Main()
' Part 1: create List of Integer values.
Dim values As List(Of Integer) = New List(Of Integer)
values.Add(1)
values.Add(5)
values.Add(9)
' Part 2: call GetEnumerator and pass to a Sub that receives IEnumerator.
Dim e As List(Of Integer).Enumerator = values.GetEnumerator()
Write(e)
End Sub
Sub Write(e As IEnumerator(Of Integer))
' Part 3: Use IEnumerator interface to display all elements.
While e.MoveNext()
Dim value = e.Current
Console.WriteLine(value)
End While
End Sub
End Module1
5
9
Consider a program that enumerates elements and performs some complex logic on the elements. The underlying collection (like List or array) may not matter as much.
And with GetEnumerator and IEnumerator, we can write the complex loop-based logic once, and reuse it for any underlying collection. All that is needed is GetEnumerator.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.