Monday, November 5, 2012

ByVal vs ByRef

ByVal vs ByRef


ByRef means that the code will manipulate the value. ByVal will manipulate a copy of the value. It is that simple as that. Check or try the sample I just made:


''' <summary>
''' This is a sample: show you the difference between byVal and ByRef
''' </summary>
''' <remarks>Check Technologies ltée 2012</remarks>
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        TextBox1.Text = 2
        Button1.Text = "addByVal"
        Button2.Text = "addByRef"
    End Sub

    Private Function addByVal(ByVal x) As Integer
        x = x * 2
        addByVal = x
    End Function
    Private Function addByRef(ByRef x) As Integer
        x = x * 2
        addByRef = x
    End Function

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Label1.Text = addByVal(TextBox1.Text)
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Label1.Text = addByRef(TextBox1.Text)
    End Sub
End Class



This is what Visual Studio 2010 looks like, a form with 2 buttons, 1 label and 1 TextBox:

When you run the code Button1 call the function addByVal while the other button calls addByRef. Inside both function, they are identical. Only the way you send the variable in the argument changes.
For your information, if you don’t put anything (byVal or ByRef) by default, is ByVal..


There are exceptions over exceptions if you are dealing with Arrays, Collections and others objects. You better check to make sure. And what is true in one language isn’t true in another language.

I am surprised that MSDN haven’t put more information.


ByVal (Visual Basic) : that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code


 ByRef (Visual Basic) : Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the argument in the calling code.

References:



The program I love to use, buy it: Visual Studio 2010 Professional (Old Version)




1 comment:

  1. In C#, simple types (int, char, string, double, float, etc.) are sent by value to a function, while more complex types are sent by reference (int[], List, MemoryStream, etc.)

    To send a simple type by reference, you add the ref method parameter before the signature of the variable.

    For example, method 1 would look like:
    int addByVal(int x)
    {
    return x * 2;
    }
    // x = x after

    Method 2 would look like
    int addByVal(ref int x)
    {
    return x * 2;
    }
    // x = 2 * x after

    There is no limit as to the number of parameters sent by ref.

    ReplyDelete