Frage

I have some simple code and I understand what it does but not why. I have a Sub and it calls another Sub called CheckIfNothing(oList). oList is a List(Of String). The Sub CheckIfNothing checks each String and if it it Nothing it will make it "". This is the code:

Public Function GiveList(oList As List(Of String))

    CheckIfNothing(oList)

    Return oList
End Function

Public Sub CheckIfNothing(oList As List(Of String))

    For Each s As String In oList
        If s Is Nothing Then
            s = ""
        End If
    Next

End Sub

So in GiveList I call CheckIfNothing and I don't return anything from CheckIfNothing and still, the oList in GiveList has no Strings that are Nothing.

I always thought you had to return the value you changed in the called function and set the value again in the sub you call the function in like this: oList = CheckIfNothing(oList). CheckIfNothing would be a function in this case.

Why isn't this necessary, and is this only in VB.NET or also the case in C#?

War es hilfreich?

Lösung

Maybe this will help explain your question. It is from MSDN regarding Visaul Basic 2013.


When passing an argument to a procedure, be aware of several different distinctions that interact with each other:

•Whether the underlying programming element is modifiable or nonmodifiable

•Whether the argument itself is modifiable or nonmodifiable

•Whether the argument is being passed by value or by reference

•Whether the argument data type is a value type or a reference type

For more information, see Differences Between Modifiable and Nonmodifiable Arguments (Visual Basic) and Differences Between Passing an Argument By Value and By Reference (Visual Basic).

This code is an example of how you can use () around your parameter to protect it from being changed.

Sub setNewString(ByRef inString As String)
    inString = "This is a new value for the inString argument."
    MsgBox(inString)
End Sub
Dim str As String = "Cannot be replaced if passed ByVal" 

' The following call passes str ByVal even though it is declared ByRef. 
Call setNewString((str))
' The parentheses around str protect it from change.
MsgBox(str)

' The following call allows str to be passed ByRef as declared. 
Call setNewString(str)
' Variable str is not protected from change.
MsgBox(str)

Passing Arguments by Value and by Reference (Visual Basic) 2013

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top