Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
In which case do we prefer 'Ref' to 'Out' and 'Out' to 'Ref' ?
Posted
Updated 11-Jul-11 22:52pm
v3
Comments
Sergey Alexandrovich Kryukov 12-Jul-11 4:53am    
Removed tag ASP.NET -- the question is general, nothing to do with ASP.NET.
--SA

Simple: If you are planning on passing a value into and out of a method via a parameter, you need ref
If you are only returning the new value, and not passing a value into the method, use out
 
Share this answer
 
Comments
Abhinav S 12-Jul-11 5:17am    
Correct. My 5.
Espen Harlinn 12-Jul-11 9:37am    
Right, my 5
Uday P.Singh 13-Dec-11 12:50pm    
5ed :)
They have different syntax and different requirements from the code implementing the method, from the binary layout on stack they are the same.

Out is the same as ref, with additional requirement: to assign some value to it before return, enforced by compile-time error. The purpose of out is to read value (optionally) and assign new value (mandatory). For ref, you can do read-only or write-only, or nothing (which makes no sense).

Also, a call should math; a keyword ref or out should be used. At the call, a ref parameter should be initialized; out does not require initialization.

[EDIT] See also my other solution, a bit more detailed: The out and ref Parameter in C#[^]. Please also see the discussion and other answers.

—SA
 
Share this answer
 
v3
Comments
Abhinav S 12-Jul-11 5:17am    
Useful. My 5.
Sergey Alexandrovich Kryukov 12-Jul-11 9:26am    
Thank you, Anhinav.
--SA
Espen Harlinn 12-Jul-11 9:36am    
A 5
Sergey Alexandrovich Kryukov 13-Dec-11 13:05pm    
Thank you, Espen.
--SA
Uday P.Singh 13-Dec-11 12:52pm    
5ed :)
Ref requires values to be assigned before passing them in.
Out requires values to be returned and no out parameters can be returned without assigning.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 12-Jul-11 9:28am    
Correct, a 5. By "returning" one should understand: a value should be assigned before return.
--SA
Abhinav S 12-Jul-11 9:56am    
I think you gave me a 1 instead of a 5. :)
Abhinav S 12-Jul-11 12:24pm    
Still not fixed. :)
Uday P.Singh 13-Dec-11 12:52pm    
5ed :)
Abhinav S 14-Dec-11 0:11am    
Thanks Uday.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900