Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Passing Reference Types

Program gif illustrates parameter passing of reference types. In this case, the variables x, y and z are all reference types. The type of x, y and y is Obj. Thus, x, y and y refer to instances of the Obj class defined on lines 3-6.

   program56640
Program: Parameter passing example: passing reference types.

The semantics of parameter passing for reference types work exactly as they do for value types: In pass-by-value, the effect of the formal parameter definition is to create a local variable of the specified type in the given method. For example, the method Two has a local variable of type Obj called y. When the method is called, the actual parameters are assigned to the formal parameters before the body of the method is executed. Since x and y are reference types, when we assign y to x, we make them both refer to the same instance of the Obj class. Therefore, the Two method modifies the original Obj instance.

In pass-by-reference, the formal parameter ends up being a reference to a reference type. For example, in the method Three the formal parameter z refers to the reference parameter x. Thus, when we create a new Obj instance and assign it to z, the referenced variable x is modified.

The output obtained produced by the method One defined in Program gif is:

1
2
2
1
1


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.