What is the difference between out and ref? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is the difference between out and ref?

In C# the ref and out keywords seem to do the same thing, I never saw any examples where they do different things. I have just been using the out keyword because I have no idea what the difference is. Help!!

1st Sep 2019, 6:51 PM
Thelegendofbrio 1606
Thelegendofbrio 1606 - avatar
9 Answers
+ 1
I think I understand now. Out variables cant be changed that much inside the method and is used to return a value, while ref can change a lot of stuff inside the method and is used to change the value inside the method.
2nd Sep 2019, 1:28 PM
Thelegendofbrio 1606
Thelegendofbrio 1606 - avatar
+ 4
Difference between Ref and Out keywords in C# The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. ... The ref is a keyword in C# which is used for the passing the arguments by a reference.
1st Sep 2019, 7:14 PM
BroFar
BroFar - avatar
+ 3
ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function. So while ref is two-ways, out is out-only. https://stackoverflow.com/questions/388464/whats-the-difference-between-the-ref-and-out-keywords
1st Sep 2019, 7:21 PM
Vahid
Vahid - avatar
+ 2
Does that mean if I use out I can use a var parameter?
1st Sep 2019, 7:20 PM
Thelegendofbrio 1606
Thelegendofbrio 1606 - avatar
+ 2
Out used when you want return from method more than one value , ref used if you want to change your variable exactly inside the method. With out you can't create construction like this: https://code.sololearn.com/cgIyphbGepOQ/?ref=app
1st Sep 2019, 7:26 PM
id001x
id001x - avatar
+ 2
Ref variables can be used inside the method before or without setting a value to them from within the method.
1st Sep 2019, 10:44 PM
Sonic
Sonic - avatar
0
So if I give an out variable to a method without already assigned a value, and attempt to assign it in the method, would that result in an error?
2nd Sep 2019, 1:08 PM
Thelegendofbrio 1606
Thelegendofbrio 1606 - avatar
0
If you use ref, the value assigned will be changed, but not with out. There can be only one ref as it changes the external values referred. It is mandatory to assign a value to a ref variable, but not to out variable. There can be as many out variables as you can.
3rd Sep 2019, 5:14 PM
Rohan Rao
Rohan Rao - avatar