Chapter 10
250
For help in determining if a variable is a value or reference types, Visual Basic
provides the IsReference function. The function returns true if a variable is a
reference type or false if a value type.
Whether to pass a parameter by value or by reference depends on what informa-
tion the function expects, the element type being passed, and in some cases
whether the type is blittable (defined below). Sometimes multiple ways can
achieve the same result.
Passing a value type by value passes a copy of the variable’s value. If the called
function changes the value of the variable or its members, the calling function
doesn’t see the change. For example, when calling ReadFile to read data from a
device, the application passes an Int32 variable that contains the number of
bytes requested from the device. The called function uses the passed value but
doesn’t have to return the value to the calling application, so the application can
pass the variable, which is a value type, by value.
Passing a value type by reference passes a pointer to the variable’s data. If the
called function changes the variable or its members, the calling application sees
the changes. An example, again using ReadFile, is passing an Int32 variable by
reference to hold the number of bytes the function returns. The called function
writes a value to the variable, and when the function returns, the calling appli-
cation sees the value written.
Passing a reference type by value also passes a pointer to the variable’s data, but
the effect varies depending on whether the type is blittable. A blittable type is a
.NET data type that managed and unmanaged code represent in the same way.
Blittable types include Byte, SByte, Int16, UInt16, Int32, UInt32, Int64,
UInt64, IntPtr, UIntPtr, Single, Double, and IntPtr as well as SafeHandles used
as IN parameters.
When an application passes a blittable, reference type by value to an unman-
aged function, the application passes a reference to the original variable. To pre-
vent the garbage collector from moving the variable while the function
executes, the CLR pins the variable in memory. The calling application sees
changes to the variable’s value but not changes to the variable’s instance. Passing
a reference to the original variable in this way reduces overhead and improves
performance compared to passing the variable by value.
An example of passing a blittable, reference type by value is passing a Byte array
in a synchronous call to ReadFile, which expects a pointer to an array that the
function will fill with data read from the device. Because a Byte array is a refer-
ence type and a Byte is a blittable type, if the application passes the array by