Wednesday, July 25, 2007

Passing Reference-Type Parameters

When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref (or out) keyword.

Passing Reference Types by Value
The following example demonstrates passing a reference-type parameter, myArray, by value, to a method, Change. Because the parameter is a reference to myArray, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, myArray.

static void Change(int[] arr)
{
arr[0]=888; // This change affects the original element.
arr = new int[5] {-3, -1, -2, -3, -4}; // This change is local.
}

Passing Reference Types by Reference
The following example demonstrates passing a reference-type parameter by reference using the ref keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.

static void Change(ref int[] arr)
{
// Both of the following changes will affect the original variables:
arr[0]=888;
arr = new int[5] {-3, -1, -2, -3, -4};
}

No comments:

Post a Comment