Difference between ByVal and ByRef?

ByRef is like a second return value. It passes a reference to the object into the function rather than the object itself. If you change the value of a ByRef parameter in the function, you will see those changes after the function ends. If that wasn't clear enough, read this and this.


If you pass in a reference, when you modify the value in the method, the variable in the call site will also be modified.

If you pass value, it's the same as if another variable is created at the method, so even if you modify it, the original variable (at the call site) won't have its value changed.

So, indeed, you should usually pass variables as value. Only pass as reference if you have an explicit need to do so.


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.