Alex Rivera | Logout

When is using the C# ref keyword ever a good idea?

Asked 2010-08-21T22:20:19.787
32

The more I see ref used in production code, the more misuse I encounter and the more pain it causes me. I have come to hate this keyword, because from a framework-building standpoint, it seems silly. When would it be a good idea to communicate to users of your code the notion of maybe changing an object reference/value out from beneath them?

By contrast, I love out keywords and I love even more when no keywords are used at all, in both cases because of the guarantees you're given when using them. Ref on the other hand makes no guarantees, except that you'll be forced to initialize the parameter before you pass it in, even though nothing may be changed about it.

I'm no sage developer though; I'm sure it's got practically applicable uses. I'd just like to know what they are.

Edit
Report

1 Answer

-1

I'm using ref quite often. Just think about functions with multiple return values. It doesn't make sense to create a return object (helper object) or even using hashtables for this purpose.

Example:

 getTreeNodeValues(ref selectedValue, ref selectedText);

Edit:

It's better to use out here - as commented.

 getTreeNodeValues(out selectedValue, out selectedText);

I'm using it for processing objects:

MyCar car = new MyCar { Name="TestCar"; Wieght=1000; }

UpdateWeight(ref car, 2000);
answered 2010-08-21T22:24:40.823

Your Answer