What is the Difference Between Out and Ref Parameters?


In C Sharp(C#) we can have three types of parameters in a function. The parameters can be In parameter (which is not returned back to the caller of the function), Out parameter and ref parameter (where by a reference to the variable is passed back).
The last two type (out and ref) mentioned looks quite similar in nature. Both parameters are used to return back some value to the caller of the function. But still there is a small but important difference between them. Both of the parameter type has been kept in the C# language for specific scenario.
The main difference between the two types is in the rule for definite assignment of them.
When we use the out parameter, The program calling the function need not assign a value to the out parameter before making the call to the function. The value of the out parameter has to be set by the function before returning the value.
The same is not true for the reference (ref) type parameter. For a ref type parameter, the value to the parameter has to be assigned before calling the function. If we do not assign the value before calling the function we will get a compiler error.

Another important thing to note here is that in case of ref parameter, the value passed by the caller function can be very well used by the called function. The called function does not have the compulsion to assign the value to a ref type parameter. But in case of the out parameter, the called function has to assign a value.

No comments:

Post a Comment