Ref and Out both are also useful for returning multiple values or output by a function. I will give an example later in this article. By default, all the functions return a single value that can either be object type or array type. But sometimes, it is necessary to have multiple output, and these keywords make us return multiple output.
Suppose, I am creating a simple calculator for getting the sum and difference of two numbers, but I don’t want to create two separate functions - one for sum and the other one for difference. So, I decided to create a function that returns both the values. This is possible by using Ref and Out keywords.
- Ref and Out, both are used for passing parameters by reference into a function.
- Ref is by-directional because it can pass the value from caller to calling function parameter and after performing the operation on this variable, calling function returns the value back to the caller function.
- Out is single-directional because the value which we pass into calling function parameter is always being discarded. So, in case of Out, it does not matter what we are passing.
- In case of Out, it is necessary to initialize the variables inside the calling function, otherwise it will give the "compile time error".
- Out and Ref work differently at run time but both are same at compile time. So, if you want to create two functions with the same names and same parameters but the only difference is Out and Ref keyword, then it will give a compile time error. We can say overloading is not possible in case of the same functions and they have only one difference, i.e. Ref and Out keyword
- Sometimes, in the variable of my caller function, we want to reflect all the changes we made in the calling function. Then, we need to use Ref and Out keyword.
- Sometimes, we want to return multiple values from a function or method, then we think about Ref and Out.
Passing parameter by value
Value inside the calling function

Value inside the caller function.

So if we want to reflect all changes on variable inside the caller function which have been done in calling function variable then we use out and ref keyword.
Now we modify the same function and use the ref Keyword with Num variable let’s see what happens.








Jaco ZwartsPosted Dec 5, 2016, 2:36 AM
Good read, thank you Asit