ref (Reference) Parameter
“ref” parameter is used to pass the value by reference from actual parameter to formal parameter i.e from callee method to the called method. In C#, a parameter declared with a “ref” modifier is a reference parameter. When you pass parameters by reference, unlike value parameters, a new location is not created for this parameter. Any changes made to the formal parameter will reflect in the actual parameter.
Example of ref Parameter
As shown in the above program snippet, any changes made to m will be reflected to n, as the parameter is passed by reference.
out (Output) Parameter
The output parameter is used to pass the result back to the calling function. ‘out’ keyword is used to declare the parameter as an Output parameter. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, it becomes an alias to the parameter in the calling method.
Example of out Parameter
In the above program, x is declared as an out parameter in calling function and as you can see, x has not been initialized. When Square function terminates, the value of q will be copied to the output parameter x.
Difference between ref and out parameter in C#
- In the reference parameter, changes made to the formal parameter reflects the actual parameter, while in out parameter, value is reflected back to the out parameter of the calling function.
- The ‘output’ actual parameter usually not assigned a value while an actual parameter declared as the reference should always be assigned a value before calling.
Note: You must assign value to the out parameter in method body; otherwise the method won’t be compiled. - Both out and ref parameters don’t create a new memory location.
- The ref and out parameters are treated differently at run-time, but they are treated the same at compile time.
Leave a Reply