I despise out's and ref's as parameters on methods. IMHO, they make code less clean and provide opportunities for side-effects. But I concede that I may not understand their usefulness which might explain part of my loathing. Please, can someone explain a valid case for out's or ref's?
C# Out and Ref – Valid Reasons to Use ‘out’ or ‘ref’ Parameter in a Method
c++
Best Answer
Basically if you need to return more than one value, it's an alternative to using something like
Tuple<,>
or a custom type to encapsulate the values. The canonical example is probablyint.TryParse
and related methods. They want to convey two pieces of information back:Now these could actually have been written using a return type of
int?
etc in this case, but it's the same principle for other cases. (For example,Dictionary<,>.TryGetValue
, where the value stored in the dictionary may legitimately be null.)I wouldn't say I despise
out
andref
parameters, but I do believe they should only be used occasionally, and only when there isn't a better alternative. Most of the uses ofref
I see on Stack Overflow are due to a misunderstanding of parameter passing.