Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Consider the methods One and Two defined in Program . The only difference between this code and the code ginve in Program is the the use of the keyword ref in the definition and use of the method Two. In this case, the formal parameter y is declared to be a reference to an int. Therefore, when the method is called, the actual parameter must also be a reference to an int. The expression ref x on line 7 provides a reference to the variable x. Thus, in this case the parameter passing is pass-by-reference.
Program: Example of pass-by-reference parameter passing.
A reference formal parameter is not a variable. When a method is called that has a reference formal parameter, the effect of the call is to associated the reference with the corresponding actual parameter. That is, the reference becomes an alternative name for the corresponding actual parameter.
A reference formal parameter can be used in the called method everywhere that a variable can be used. In particular, if the reference formal parameter is used where its value is required, it is the value of the actual parameter that is obtained. Similarly, if the reference parameter is used where a reference is required, it is a reference to the actual parameter that is obtained. Therefore, the output obtained produced by the method One defined in Program is:
1 2 2