Search code examples
c#parameterspass-by-referencepass-by-value

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


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

Solution

  • 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"