Passing a List Enumerator to a Function

It seems that enumerating a list enumerator to a "byval" function is completely different than passing it a "byref". Essentially, passing a byval regularly does NOT change the caller's enumerator.Current value, even if the function advances the counter. I was wondering if anyone knows why this is so. Is the enumerator primitive, as a whole, without reference to the object, and, therefore, changes in it are not reflected in the caller?

Here is a sample code:

This function is a byte and gets stuck in an infinite loop, spitting out messages "1", because the enumerator "current" never moves into the past 5:

Public Sub listItemsUsingByValFunction()
    Dim list As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

    Dim enumerator = list.GetEnumerator()
    enumerator.MoveNext()
    While enumerator.Current <= 5
        listFirstItemByVal(enumerator)
    End While
End Sub
Private Sub listFirstItemByVal(ByVal enumerator As List(Of Integer).Enumerator)
    MsgBox(enumerator.Current)
    enumerator.MoveNext()
End Sub

This, on the other hand, works as one would expect:

Public Sub listItemsUsingByRefFunction()
    Dim list As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

    Dim enumerator = list.GetEnumerator()
    enumerator.MoveNext()
    While enumerator.Current <= 5
        listFirstItemByRef(enumerator)
    End While
End Sub
Private Sub listFirstItemByRef(ByRef enumerator As List(Of Integer).Enumerator)
    MsgBox(enumerator.Current)
    enumerator.MoveNext()
End Sub

, listFirstItem__ byref.

+5
2

, , , List(Of T).Enumerator Struct, Class, . , , , , , MoveNext

+8

, , Strict On. , , .

Public Sub listItemsUsingByValFunction()
    Dim list As New List(Of Integer)(New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

    Dim enumerator As IEnumerator(Of Integer) = list.GetEnumerator()
    enumerator.MoveNext()
    Debug.WriteLine("S " & enumerator.Current)
    Stop
    Do
        Debug.WriteLine("W " & enumerator.Current)
        If Not listFirstItemByVal(enumerator) Then Exit Do
    Loop
End Sub

Private Function listFirstItemByVal(ByVal enumerator As IEnumerator(Of Integer)) As Boolean
    Debug.WriteLine("F " & enumerator.Current)
    Return enumerator.MoveNext()
End Function

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    listItemsUsingByValFunction()
End Sub
0

All Articles