+ 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!!
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.
+ 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.
+ 4
here is a quick resource:
https://www.geeksforgeeks.org/difference-between-ref-and-out-keywords-in-c-sharp/amp/
+ 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
+ 2
Does that mean if I use out I can use a var parameter?
+ 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
+ 2
Ref variables can be used inside the method before or without setting a value to them from within the method.
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?
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.