Link to home
Start Free TrialLog in
Avatar of username1
username1

asked on

VB.Net, ByVal and ByRef

Hi Experts,

In VB.Net.
When we should use ByVal and when use ByRef to pass an array to a Sub/Function?
I have tested ByVal and ByRef and got the same results.....

Thank you in advance.
Avatar of saxaboo
saxaboo

Hi,

indeed, as long as you don't try to do any assignment in your sub/func, byval and byref will behave the same.

Here is the explanation : as its name doesn't suggest, a byval parameter is passed by reference ! ByRef is equivalent to C#'s ref keyword.

Here is a code snippet that should help you in identifying the difference :


'in your sub Main()
Dim a as String() = new String(){"0"}
test(a)

'change to  byref & test it
public sub test(byval s as String())
     s = new String(){"1","2","3"}
end sub

HTH,

-S
Avatar of username1

ASKER

Thank you.

I am not understand String()....but my example shows I got the same result when did assignment in the sub:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim a(0) As Integer
        test(a)
        MessageBox.Show(a(0))   'return 1 for both ByRef and ByVal.
    End Sub

    Private Sub test(ByRef s() As Integer)
        s(0) = 1
    End Sub
byval creates a new pointer for the array , byref passes the same pointer, as you found, it makes little difference.

the differenct is when you have a single object, as I understand it, byval passes a clone of the object whereas byref passes the object pointer.

in practice even though there is little difference you should use byref when you pass the referance, no point creating a new pointer if you dont need to and it makes the code understandable: the array is passed as a referance, not as a value.
ASKER CERTIFIED SOLUTION
Avatar of saxaboo
saxaboo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial