Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ByVal and ByRef?

What is the difference? I always use ByVal, but, I don't really have a good idea of when should I and when not...

like image 850
Voldemort Avatar asked Feb 05 '11 18:02

Voldemort


1 Answers

ByRef = You give your friend your term paper (the original) he marks it up and can return it to you.

ByVal = You give him a copy of the term paper and he give you back his changes but you have to put them back in your original yourself.

As simple as I can make it.

Why to use ByRef:
ByRef will pass the POINTER to the object you are passing. If you are in the same memory space, this means passing just the 'word' not the object. The method you are passing it to can make changes in the original object, and does not need to pass them back at all, as they are in the original object. Useful for making large data passes faster. You can also use ByRef to allow use of a SUB rather then a FUNCTION (In VB) since it does not need to pass back the object.

Why not to use ByRef:
Since the method has access to the original, any changes made will be immediate and permanent. If the method fails, the object could be corrupted. Using ByVal will make a copy, pass the whole copy into the method, and then the method will process the info and either return a copy back, report information or do nothing.

like image 106
Tom Vande Stouwe Avatar answered Sep 23 '22 19:09

Tom Vande Stouwe