Quizzma Latest Questions

Difference Between ByVal And ByRef

What is the main difference between ByVal and ByRef? Where are they used in Visual Basic Programming? Explain your answers with examples.




Related Questions

Leave an answer

Leave an answer

3 Answers

  1. Sub Main()
    Dim message As String = “Hello”
    AppendExclamationByRef(message)
    Console.WriteLine(message) ‘ Output: Hello!
    End Sub

    Sub AppendExclamationByRef(ByRef str As String)
    str = str & “!”
    End Sub

  2. Sub Main()
    Dim message As String = “Hello”
    AppendExclamationByVal(message)
    Console.WriteLine(message) ‘ Output: Hello
    End Sub

    Sub AppendExclamationByVal(ByVal str As String)
    str = str & “!”
    End Sub

    • ByVal passes a copy of the variable, changes made within the function do not affect the original variable.
    • ByRef passes a reference to the variable, changes made within the function affect the original variable.

    Choosing between ByVal and ByRef depends on whether you want the called function to have the ability to modify the original variable or not.