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.


Think of a non-ref parameter as being a pointer, and a ref parameter as a double pointer. This helped me the most.

You should almost never pass values by ref. I suspect that if it wasn't for interop concerns, the .Net team would never have included it in the original specification. The OO way of dealing with most problem that ref parameters solve is to:

For multiple return values

  • Create structs that represent the multiple return values

For primitives that change in a method as the result of the method call (method has side-effects on primitive parameters)

  • Implement the method in an object as an instance method and manipulate the object's state (not the parameters) as part of the method call
  • Use the multiple return value solution and merge the return values to your state
  • Create an object that contains state that can be manipulated by a method and pass that object as the parameter, and not the primitives themselves.

You could probably write an entire C# app and never pass any objects/structs by ref.

I had a professor who told me this:

The only place you'd use refs is where you either:

  1. Want to pass a large object (ie, the objects/struct has objects/structs inside it to multiple levels) and copying it would be expensive and
  2. You are calling a Framework, Windows API or other API that requires it.

Don't do it just because you can. You can get bit in the ass by some nasty bugs if you start changing the values in a param and aren't paying attention.

I agree with his advice, and in my five plus years since school, I've never had a need for it outside of calling the Framework or Windows API.

Tags:

C#

Ref