I understand that if I pass a value-type (int
, struct
, etc.) as a parameter (without the ref
keyword), a copy of that variable is passed to the method, but if I use the ref
keyword a reference to that variable is passed, not a new one.
But with reference-types, like classes, even without the ref
keyword, a reference is passed to the method, not a copy. So what is the use of the ref
keyword with reference-types?
Take for example:
var x = new Foo();
What is the difference between the following?
void Bar(Foo y) {
y.Name = "2";
}
and
void Bar(ref Foo y) {
y.Name = "2";
}
There are cases where you want to modify the actual reference and not the object pointed to:
When you pass a reference type with the ref keyword, you pass the reference by reference, and the method you call can assign a new value to the parameter. That change will propagate to the calling scope. Without ref, the reference is passed by value, and this doesn't happen.
C# also has the 'out' keyword which is a lot like ref, except that with 'ref', arguments must be initialized before calling the method, and with 'out' you must assign a value in the receiving method.
Jon Skeet wrote a great article about parameter passing in C#. It details clearly the exact behaviour and usage of passing parameters by value, by reference (
ref
), and by output (out
).Here's an important quote from that page in relation to
ref
parameters:You can change what
foo
points to usingy
: