In C# given a function with the below signature
public static void Foo(ref int x, ref int y)
If the function was called using
int A = 10;
Foo(ref A, ref A)
Inside the function Foo is it possible to test that the x and y arguments reference the same variable? A simple equivalent test of x and y isn't sufficient as this is also true in the case two different variable have the same value.
If you're willing to use unsafe code, you can compare the underlying variable addresses:
public static bool Foo(ref int a, ref int b)
{
unsafe
{
fixed (int* pa = &a, pb = &b)
{
// return true iff a and b are references to the same variable
return pa == pb;
}
}
}
(Edited to remove unsafe
from method signature, based on @Michael Graczyk's comment.)
You could use Object.ReferenceEquals(x, y)
to determine whether x
and y
were references to the same object.
Edit: As was pointed out by Kirk Woll (confirmed in this article on MSDN), this method doesn't work for value types (due to boxing). You can get around this by changing the parameter types on the method from int
to object
(of course, this means you will also have to pass an object
variable to the method - this can still be an int
, though).
i.e. the method becomes:
public static void Foo(ref object x, ref object y) {
Console.WriteLine("x and y the same ref: {0}", Object.ReferenceEquals(x, y));
}
and calling it with:
object A = 10;
Foo(ref A, ref A);
will result in "x and y are the same ref: True"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With