What is difference between ref and out in c# functions? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is difference between ref and out in c# functions?

Ref vs out

2nd Sep 2016, 5:47 PM
Omer SALAJ
Omer SALAJ - avatar
3 Answers
+ 3
The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refer to the new object. Out is used when you want to return a value and re-use it. The only time I can realistically see using Out is when you want to return more than one value. If you're only returning one value you can just use the 'return' keyword.
5th Sep 2016, 11:07 AM
Mike
Mike - avatar
0
As far as I know, the only difference is using ref with an unassigned variable will cause an error. I guess out is preferred when the intent is to create or reassign without checking what the variable contains.
3rd Sep 2016, 3:32 PM
Nsyse
Nsyse - avatar
0
Well, if not more it makes the API and what to expect from the function call clearer. Besides working on the actual data instead of a copy (pass by reference), using ref you can read APIs like "variables I pass in might get modified". Using out you can think of the API like "I have to declare this variable as the function will initialize it or override its current value". This is also useful if you need to return multiple return values of different types, although it isn't common to do so.
4th Sep 2016, 11:11 PM
René Schindhelm
René Schindhelm - avatar