Search code examples
c#ref

In C#, where do you use "ref" in front of a parameter?


There are a number of questions already on the definition of "ref" and "out" parameter but they seem like bad design. Are there any cases where you think ref is the right solution?

It seems like you could always do something else that is cleaner. Can someone give me an example of where this would be the "best" solution for a problem?


Solution

  • In my opinion, ref largely compensated for the difficulty of declaring new utility types and the difficulty of "tacking information on" to existing information, which are things that C# has taken huge steps toward addressing since its genesis through LINQ, generics, and anonymous types.

    So no, I don't think there are a lot of clear use cases for it anymore. I think it's largely a relic of how the language was originally designed.

    I do think that it still makes sense (like mentioned above) in the case where you need to return some kind of error code from a function as well as a return value, but nothing else (so a bigger type isn't really justified.) If I were doing this all over the place in a project, I would probably define some generic wrapper type for thing-plus-error-code, but in any given instance ref and out are OK.