What is the main difference between ByVal and ByRef? Where are they used in Visual Basic Programming? Explain your answers with examples.
Question & Answer
Difference Between ByVal And ByRef
3 Answers
Verified archive- 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.
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
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