top of page

VB's ByVal and ByRef : Why should you care?

If you've coded VB for some time, you probably have noticed that parameters are declared either as "ByVal" or "ByRef" --- but do you know what they mean and what they are for?

Today we'll look at these two directives using a real world scenario to describe it further and then I'll give you a VB 6.0 source code to demonstrate exactly what the effects of using either.

Imagine you have a picture of you and your friend from when you were still young. This is the only copy of the picture you have and so you decided to scan it and gave a digital copy to your friend.

Your friend can modify the image however he/she wants but it only has an effect on that digital copy. The one in your possession stays intact no matter how much change your friend makes on his digital copy.

But if you gave the original copy and your friend altered it, then the change is permanent.

In this example, when you gave a digital copy of the picture to your friend, this is similar to how "ByVal" works --- you just "give a copy", but when you gave the original copy of the picture, then it is similar to how "ByRef" works --- you gave the exact copy.

So how do we translate this to programming? What's the relevance of that, now that you know it?

Let's take a look at a simple VB 6.0 program to illustrate both of them.

Say you are writing a financial application for a company that computes the salary of their internal employees and you have several routines that works on the value of the employee salary.

If the salary variable is being passed on to subroutines or functions, then you should be aware of "how" you want to pass it by.

If you look at the code snippet on the right, we initiated the value of salary to 100.

We simulate calling a method that accepts the salary "by value" and then "by reference". We printed the value of it from inside the method and outside so we can compare or see the differences.

Now look at the "Immediate" screen below and you'll see the effects of both ByVal and ByRef.

Passing "by value" does not change the actual value of the variable outside of it.

While inside, it can change the value but as soon as the method exits, the original value is retained.

However, "by reference" changed the value of the variable even when the method exited.

You need to be aware of this behavior when you're writing codes so you don't encounter unexpected or unintended results.

So is "ByRef" a bad thing and shouldn't be used?

Of course not.

There are uses for "ByRef" and if you know someone writing in C++, I'm sure they use this technique a lot.

Point is, know the tools or techniques that you're using; use them when it makes sense to use them and when you know exactly "why" you're using them.

bottom of page