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
}
}
obj
can't be GC'd at that point since theres a reference to it. the CLR is smarter than you think. – Daniel A. WhiteF
cannot (in normal C#) hold a reference tovalue
after it's finished executing. There wouldn't be any case whereobj
is a candidate for garbage collection whileF
executes. – Rob