Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a valid reason to use an 'out' or 'ref' parameter in a method?

Tags:

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?

like image 304
Byron Sommardahl Avatar asked Oct 15 '11 19:10

Byron Sommardahl


People also ask

What is the use of ref and out parameter in C#?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.

Why do we use out parameter?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

What is use of ref keyword in method?

The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference.

What is the difference between reference parameters and output parameters when should you use each?

The reference parameters are used to pass parameters to the method by reference. The output parameters are used to pass the result back from the method. In C#, out keyword is used for output parameters and ref keyword is used to reference parameters.


1 Answers

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.

like image 167
Jon Skeet Avatar answered Oct 11 '22 01:10

Jon Skeet