• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1010
  • Last Modified:

Byref and Byval

I would like someone to give me a simple and clear illustration of using Byval and Byref in VB example.

  • 2
1 Solution
Éric MoreauSenior .Net ConsultantCommented:
Hi jskfan,

Consider this code snippet:
Private Sub Command1_Click()
Dim i As Integer
Dim j As Integer
    i = 0
    j = 0
    Call Test(i, j)
    MsgBox "i=" & i & vbCrLf & "j=" & j
End Sub

Private Sub Test(ByVal p1 As Integer, ByRef p2 As Integer)
    p1 = 10
    p2 = 20
End Sub

2 variables (i and j) are created and initialized to 0.
Then both variables are passed to the Test method:
-p1 receives a copy of the value contained in i (a 0 value) and creates a new place in memory to store this value.
-p2 receives a reference (it is a pointer) to the j variable.

when p1 is modified, the copy is modified but the original remains untouched.
when p2 is modified, since p2 is a reference to the original place in memory where the value of j is stored, the original value is modified.

that's why the msgbox prints i=0 and j=20
jskfanAuthor Commented:
I guess I figured it out ...

Private Sub calculatesum(ByVal numb1 As Integer, ByVal numb2 As Integer, ByVal totalsum As Integer)
        totalsum = totalsum + numb1 + numb2
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim x, y, z
        x = 5
        y = 5
        z = 7
        Me.calculatesum(x, y, z)

    End Sub
jskfanAuthor Commented:
thanks, your example is much more simple and clear.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now