When to use ref and when it is not necessary in C#

Short answer: read my article on argument passing.

Long answer: when a reference type parameter is passed by value, only the reference is passed, not a copy of the object. This is like passing a pointer (by value) in C or C++. Changes to the value of the parameter itself won’t be seen by the caller, but changes in the object which the reference points to will be seen.

When a parameter (of any kind) is passed by reference, that means that any changes to the parameter are seen by the caller – changes to the parameter are changes to the variable.

The article explains all of this in more detail, of course 🙂

Useful answer: you almost never need to use ref/out. It’s basically a way of getting another return value, and should usually be avoided precisely because it means the method’s probably trying to do too much. That’s not always the case (TryParse etc are the canonical examples of reasonable use of out) but using ref/out should be a relative rarity.

Leave a Comment