C# passing class member as ref parameter

1.7k views Asked by At

I do not understand why it is possible to pass a class instance member as ref parameter to a function.

The object could be moved by garbage collection while the function is executing, invalidating the reference.

Yet this seems to be allowed and works. Does it mean "ref" parameters are more than just a native pointer under the hood?

class A
{
    public int Value;
}

class Test
{
    static void F(ref int value)
    {
        value = 7;
    }

    static void Main()
    {
        A obj = new A();
        // obj can be moved by GC, so "ref obj.Value" cannot be a native pointer under the hood
        F(ref obj.Value);  
        System.Console.WriteLine(obj.Value);  // Prints 7
    }
}
1

There are 1 answers

0
Joel Coehoorn On BEST ANSWER

Does it mean "ref" parameters are more than just a native pointer under the hood?

Yes, that's exactly what it means. If it were just a pointer, they'd call it a pointer instead of a reference. Instead, for references the GC knows about the original object and correctly tracks things, so the reference stays with the object and the object won't be collected until the method exits.