Passing ByRef and ByVal VB.NET

A

Andy Read

Dear all,

I thought I understood passing parameters ByVal and ByRef but I
clearly don't! If I define a simple class
of:

Public Class Person
Public Name as String
Public Age as Integer
End Class

Then pass a person object to a method 'ByVal'

Public Sub ChangePerson(ByVal Person as Person)
Person.Name = "MyName"
Person.Age = 22
End Sub

Why are the values Name and Age changed when I'm passing by value? I would
expect this behaviour when I'm passing by reference. I'm confused...(It's
not difficult!)

Any pointers to set me straight would be appreciated!

Thanks
 
G

GriffithsJ

Andy

I'm not entirely sure how things work in .Net since I'm really a VB6
developer, but the same is true with VB6.

ByVal will not affect simple things like strings, but it does update the
object's properties. I'm not exactly sure of the reason, but I believe it's
to do with the fact that ByRef and ByVal are actually talking about whether
the object pointer is passed by reference or by value...the actual object
itself is a single object in memory. Passing an object pointer by val or by
ref is really meaningless (the default should be byVal)

Maybe someone can provide the "perfect" answer.

Griff
 
C

Charles Law

Hi Andy

Hopefully the following expansion of your example will illustrate the
difference.

Public Class CPerson
Public Name as String
Public Age as Integer
End Class

Public Sub ChangePerson1(ByVal Person as CPerson)
' These lines will always change Name and Age
Person.Name = "MyName"
Person.Age = 22

' The next line will have no effect on the caller
Person = New CPerson

End Sub

Public Sub ChangePerson2(ByRef Person as CPerson)
' These lines will always change Name and Age
Person.Name = "MyName"
Person.Age = 22

' This line will affect the caller
Person = New CPerson

End Sub

As you will see, the only difference between ChangePerson1 and ChangePerson2
is the ByVal / ByRef parameter.

In each case, the function is passed a CPerson object. In the first the
pointer to the object is passed by value, therefore it will not affect the
callers pointer to the object. In the second case the function is passed a
reference to this pointer. If you change it it will also change the caller's
pointer.

In essence, the object is always passed by reference (in a pointer) but the
pointer is the thing that is affected. The reason for this is that if the
entire object were passed by value then the function call would have to
perform a byte-by-byte copy of the object, and this could be a very costly
overhead for large objects.

HTH

Charles
 
A

Andy Read

Thanks to all for such speedy replies! And for giving such detailed
explanations.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top