My code is as follows
class MyClass
{
static int iField = 42;
static void Test(ref int arg)
{
unsafe
{
fixed(void* pField = &iField)
fixed(void* pArg = &arg)
{
Console.WriteLine ("{0},{1}",(int)pArg,(int)pField);
//output: 165451772,165451772
}
}
}
static void Main()
{
Test(ref iField);
}
}
I’d like to know if taking address of ref parameters is as reliable as it showed above in the test.
As far as I know, yes while you are in the
fixedblock, the GC will not relocatearg. Once outside thefixedblock the variable is unpinned and thus subject to relocation by the GC.About a
staticstruct/class/field keeping it’s address fixed in memory, the answer is no. They are subject to relocation as any other object. There is not garantee per se that there will be no future relocation in memory just because it is marked asstatic.The significance of
statichas to do with the knowledge and certainties the compiler has at compile time of a certain class/struct/field what have you. It has nothing to do with memory locations and them being fixed or not, etc. In Eric Lippert’s words: