Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Test if C# ref Arguments Reference the Same Item

Tags:

c#

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.

like image 440
Paul Dixon Avatar asked Jul 16 '12 01:07

Paul Dixon


2 Answers

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.)

like image 150
drf Avatar answered Nov 04 '22 10:11

drf


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"

like image 34
Bradley Smith Avatar answered Nov 04 '22 09:11

Bradley Smith