Home   Cover Cover Cover Cover
 

Parameter passing modes

Question: Discuss the advantages and disadvantages of ref parameters, out parameters and parameters that are returned as a function result.

ref parameters:

+ They can be used to implement transient parameters, i.e. parameters that are passed to a method, changed there and returned from the method to its caller again. Without ref parameters one would need both a value parameter and a function return value.
+ They can be used to implement methods with multiple transient parameters in which values can be returned to the caller, whereas functions can only return a single value.
+ Actual ref parameters are not copied to their formal parameters but are passed by reference (i.e. only their address is passed). For large parameters this is more efficient than copying.
- ref parameters can lead to side effects, because a formal ref parameter is an alias of the corresponding actual parameter. If the method modifies a formal ref parameter the corresponding actual parameter changes as well.

out parameters:

+ They can be used to write methods with multiple return values, whereas a function can have only a single return value.
+ Like ref parameters, out parameters are passed by value, i.e. only their address is passed and not their value. For large parameters this is more efficient than copying.
+ The compiler makes sure that a method assigns values to all its out parameters before it returns.
- The use of out parameters can lead to side effects, because a formal out parameter is an alias of its corresponding actual parameter. If the method modifies its formal out parameter the actual parameter changes as well.

Function return values:

+ There are no side effects.
+ The return value can be ignored by the caller, but this can also be seen as a disadvantage.
- A method cannot return multiple function result values.