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

Pass By Value

 

Consider the pair of C# methods defined in Program gif. On line 7, the method One calls the method Two. In general, every method call includes a (possibly empty) list of arguments. The arguments specified in a method call are called actual parameters . In this case, there is only one actual parameter--y.

   program56564
Program: Example of pass-by-value parameter passing.

On line 11 the method Two is defined as accepting a single argument of type int called y. The arguments which appear in a method definition are called formal parameters . In this case, the formal parameter is a value type.

The semantics of pass-by-value work like this: 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 int called y. When the method is called, the values of the actual parameters are used assigned to the formal parameters before the body of the method is executed.

Since the formal parameters give rise to local variables, if a new value is assigned to a formal parameter, that value has no effect on the actual parameter. Therefore, the output obtained produced by the method One defined in Program gif is:

1
2
1


next up previous contents index

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