2
votes

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
obj can't be GC'd at that point since theres a reference to it. the CLR is smarter than you think.Daniel A. White
F cannot (in normal C#) hold a reference to value after it's finished executing. There wouldn't be any case where obj is a candidate for garbage collection while F executes.Rob
@DanielA.White It cannot be GC'd, but it can be moved by GC.kaalus
@Rob It cannot be garbage collected, but can be moved by the collector.kaalus
This post may be of interest.Rob

1 Answers

3
votes

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.