Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list's enumerator to a function

It looks like passing a list's enumerator to a function "byval" is quite different than passing it "byref". Essentially, regular "byval" passing will NOT change the caller's "enumerator.Current value", even if the function advances the enumerator. I was wondering if anyone knows why this is the case? Is an enumerator a primitive like an integer, without an object reference, and hence changes to it don't get reflected in the caller?

Here is the sample code:

This function is byval, and gets stuck in an infinite loop, spitting out "1" message boxes, because the enumerator's "current" never advances 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 just 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

The difference between the two functions is only whether the listFirstItem__ function accepts a byval or a byref enumerator.

like image 690
Michael Zlatkovsky - Microsoft Avatar asked Dec 02 '11 17:12

Michael Zlatkovsky - Microsoft


People also ask

How do you pass an enum into a method?

enums are technically descendants of Enum class. So, if you want to use only Enum's standard methods in your method (such as values()), pass the parameter like this: static void printEnumValue(Enum generalInformation) See, that the only thing you have to change is the capital letter E.

Can we pass enum by reference?

If they represent similar things, why not create a data structure which contains all the required data and will then easily be passed by reference. That's a valid point.

How do you pass enum as parameters in Rust?

You cannot. It is not possible to pass types as function parameters. Enum variants are not types to start with.


1 Answers

The reason why you're seeing this behavior is that List(Of T).Enumerator is a Struct and not a Class as is commonly expected. So when you pass the enumerator you pass a copy of it and hence only that copy gets updated when you call MoveNext

like image 68
JaredPar Avatar answered Oct 18 '22 14:10

JaredPar