C# Out and Ref – Valid Reasons to Use ‘out’ or ‘ref’ Parameter in a Method

c++

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?

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 probably int.TryParse and related methods. They want to convey two pieces of information back:

  • The parsed value
  • Whether or not parsing succeeded.

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 and ref parameters, but I do believe they should only be used occasionally, and only when there isn't a better alternative. Most of the uses of ref I see on Stack Overflow are due to a misunderstanding of parameter passing.

Related Question