- When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
- When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable.
In essence, passing an argument by value to a function means that the function will have its own copy of the argument – its value is copied. Modifying that copy will not modify the original object.
However, when passing by reference, the parameter inside the function refers to the same object that was passed in – any changes inside the function will be seen outside.
C# Example
In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref
, or out
keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in
modifier. For simplicity, only the ref
keyword is used in the examples in this topic. For more information about the difference between in
, ref
, and out
, see in, ref, and out.
// Passing by value.
// The value of arg in Main is not changed.
arg = 4;
squareVal(arg);
Console.WriteLine(arg);
// Output: 4
// Passing by reference.
// The value of arg in Main is changed.
arg = 4;
squareRef(ref arg);
Console.WriteLine(arg);
// Output: 16
Sources:
Comments