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?
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.
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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With