I have made some ref keyword tests and there is one think I can\'t understand:
static void Test(ref int a, ref int b)
{
Console.WriteLine(In
This cannot be done directly in C#.
You can however implement it in verifiable CIL:
.method public hidebysig static bool Test(!!T& a, !!T& b) cil managed
{
.maxstack 8
ldarg.0
ldarg.1
ceq
ret
}
Tests
int a = 4, b = 4, c = 5;
int* aa = &a; // unsafe needed for this
object o = a, p = o;
Console.WriteLine(Test(ref a, ref a)); // True
Console.WriteLine(Test(ref o, ref o)); // True
Console.WriteLine(Test(ref o, ref p)); // False
Console.WriteLine(Test(ref a, ref b)); // False
Console.WriteLine(Test(ref a, ref c)); // False
Console.WriteLine(Test(ref a, ref *aa)); // True
// all of the above works for fields, parameters and locals
Notes
This does not actually check for the same reference, but even more fine-grained in that it makes sure both are the same 'location' (or referenced from the same variable) too. This is while the 3rd line returns false even though o == p returns true. The usefulness of this 'location' test is very limited though.