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.
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.
List
Of Integers, and then in 3 subsequent calls to Add, we add 3 elements to the List
.GetEnumerator
. This returns a typed Enumerator, and we can pass this object as an IEnumerator
(it implements IEnumerator
).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
.