What is the use of "ref" for reference-type variables in C#?

Andreas Grech picture Andreas Grech · Jun 7, 2009 · Viewed 39.9k times · Source

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";
}

Answer

user7116 picture user7116 · Jun 7, 2009

You can change what foo points to using y:

Foo foo = new Foo("1");

void Bar(ref Foo y)
{
    y = new Foo("2");
}

Bar(ref foo);
// foo.Name == "2"