ByVal vs ByRef (Visual Basic)

The issue with byVal and byRef doesn't seems hard, but can be confusing.

Explanation from MSDN is not very nurturing..

Using just 6 tests, we can learn about it.

Download the code (VB.NET Visual Studio 2008 SP1) or VB6 (Visual Studio 98)

Simple Explanation:

Before that, let's define some terminologies..

There are two types of variables,
  1. Value-type (Integer, long, string)
  2. Reference-type (object such as collection, custom object and etc)
A 'called procedure' is a method of class which is invoked by a 'calling procedure' where the latter is responsible to instantiate everything.

In VB6, a parameter is by default ByRef. By default means you do not explicitly specify that it should be byVal or byRef; then it assume to be byRef.

In VB.NET, a parameter is by default ByVal.

According to this site..

When you declare a variable (either value-type or reference-type), you will allocate a memory space of it. This applies to parameters as well. This means that...

If you pass a variable byVal, a new memory location is created. ByRef no new memory location will be created.

So, in a humble way, we can say that the purpose of byVal or byRef is to tell the compiler whether or not to create new memory location.

For ByVal, technically you do not make a copy of the object, but thew new variable will reference back to the original object. And only for reference-type variable, you can update values back (from the 'called procedure') to the 'calling procedure'.

Thus, if you pass an object (reference-type variable) byVal and then set it to nothing at the 'called procedure', the 'calling procedure' will not be affected because the original memory location still untouched.

So, byVal usage is pretty obvious. But what about usage of byRef ? There three obvious usages:
  1. Update the value of a value-type variable back to the calling procedure.
  2. Terminate a reference-type variable (object) from called procedure
  3. Replace a new object to the calling procedure.

It is easier to understand this from the codes.