ByVal vs. ByRef (and also Value Type vs. Reference Type)

Published 17 July 06 07:51 PM | adrian

There are different behaviours of passing a parameter using ByVal and ByRef between Value Type and Reference Type.

For Value Type (most primitives and Structure objects):

  • ByVal copies the value of the parameter. Changes will not affect original object.
  • ByRef uses the value of the parameter. Changes will affect original object.

For Reference Type (Class objects):

  • ByVal copies the pointer to the value of the parameter. Changes will affect the original object. Unless you changed the reference of the object (e.g.: assigning a different object to the parameter, setting the parameter to Nothing)
  • ByRef uses the pointer to the value of the parameter. Changes will affect the original object, including reference changes.

Now, things get interesting when you're assigning a local variable to the referenced object (a.k.a. doing operation with the parameter outside the original method call). It seems that when you do that, the local variable copied the reference to the referenced object (just like ByVal). So when you modify the value of local variable, the changes will affect the original object, but reference changes will not.

Is it any way possible to keep references even outside the method call?

Share this post: | | | |
Filed under:

Comments

# adrian said on July 18, 2006 12:27 PM:

Hmm..setahu gw...byval ato byref itu cuma ngaruh kl tipenya adalah value type. tapi kalo class instance itu selalu dipassing byref gak perduli dikasih keyword byval ato byref didepannya. Why? karena variabel yg dideklarasi dengan tipe kelas tertentu hanya berfungsi sebagai reference ke instance dari kelas tersebut di memori.

Kalo di C++ sepertinya bisa pake keyword "const" supaya param yg dipass byref gak bisa dirubah. Kl di C# ato VB.Net gw belum tahu.

CMIIW

# adrian said on July 18, 2006 01:26 PM:

Maksudnya gini, kalau menggunakan ByVal, selalu ada penggandaan (copy) dari object yang dikirim lewat parameter. Nah, object ini akan berbeda antara Value Type dan Reference Type. Kalau Value Type, objectnya variabel itu sendiri, sedangkan kalau Reference Type, objectnya pointer.

Bedanya nanti ketika menggunakan ByRef untuk Reference Type. Object yang dimasukkan bisa diubah seenak hati, sama seperti ByRef untuk Value Type. Kalau menggunakan ByVal untuk Reference Type, perubahannya hanya di dalam object tersebut, referencenya tidak dapat diubah menjadi object lain (walaupun tipenya sama).