Passing parameters To A function By Value And By Reference

What is Pass by Value?

When we pass a parameter to a function by value, the parameter value from the caller is copied to the function parameter. Consider the below Example.

// The Function
private void PassByVal_X(int x)
{
    // Increment the value passed in
    x++;
}
// Calling Code
int testPassByVal = 10;
PassByVal_X(testPassByVal);

In the example, the caller passed the testPassByRef by value to the function PassByVal_X. The value of 10 from testPassByValue is copied to the parameter x.

What is Pass by Reference?

When we pass a parameter to a function by reference, the reference to the actual value of the caller is copied to the function parameter. So, at the end there are two references pointing to the same value, one from the caller, and one from the function.

Have a look at the below example.

private void PassByRef_X(ref int x)
{
    // Increment the value passed in
    x++;
}
// Calling Code
int testPassByRef;
testPassByRef = 10;
PassByRef_X(ref testPassByRef);
  1. In this example, the variable x and the variable testPassByRef are pointing to the same location where the value 10 is stored.
  2. Note the usage of the ref keyword. We are indicating to the compiler that the value is passed by reference.
  3. Since the value is passed by reference, the increment of value x inside the function is reflected back to the caller in the variable testPassByRef.
  4. When we are passing by reference, the variable should be initialized. Otherwise, we will get a compilation error.

What is Pass by Reference with OUT

When we pass the parameter by reference, the compiler expects that we should initialize it. If there is a situation in which an object is declared outside the function, and the same variable will be assigned some value inside the function, then we should go for Pass by reference, but not with ref. Because the ref expects that the value should be initialized. The Out keyword is used in this situation.

Both ref and out are meaning that we are passing by reference. The only difference is for out. The variable is not required to be initialized before passing it as a parameter.

Look at the below example.

private void PassByRefOut_X(out int x, int y)
{
    // Assign some value by multiplying y with y
    // x is assigned first here, after the assignment
    x = y * y;
}
// Calling Code
int testPassByRefOut;
PassByRefOut_X(out testPassByRefOut, 10);

Note the usage of out keyword. It implies that the parameter is still treated as Pass By Reference. But, now, we need not initialize it, and it must get assigned inside the function.


Similar Articles