Is it possible to compare two managed references (of type ref T) if they are equal? I don't mean references to objects, but references to variables. Example:
public static bool Compare(ref int a, ref int b)
{
return ref a == ref b; //something like that, not possible this way in C#
}
int x, y;
Compare(ref x, ref x); //true
Compare(ref x, ref y); //false
You can use the official Microsoft NuGet package System.Runtime.CompilerServices.Unsafe to accomplish this without having to mark your method as unsafe.
using System.Runtime.CompilerServices;
static void Main()
{
int value = 0;
ref int ref1 = ref value;
ref int ref2 = ref value;
Debug.Assert(Unsafe.AreSame(ref ref1, ref ref2));
}
Do note that I'd argue this method is not really Unsafe and perhaps should be moved to another class/package along with Unsafe.SizeOf.
The definitive reference (no pun intended) is here - Equality Comparisons (C# Programming Guide).
You can compare two objects of type T for reference equality by using Object.ReferenceEquals if (and so far as I know only if) T is a reference type.
As Haedrian points out, this is not possible for value types even when they are passed by reference due to boxing in the call to ReferenceEquals.
int x = 0, y = 0;
IsSameReference(ref x, ref x).Dump(); // Passing the same value type variable twice, by reference. We want a result of 'true'
IsSameReference(ref x, ref y).Dump(); // We expect 'false'
public static bool IsSameReference(ref int a, ref int b)
{
return Object.ReferenceEquals(a, b);
}
Both calls dump false. (Note I renamed the function Compare as that is usually used for sort-ordering comparisons).
Essentially then, where T can be of any type, the answer is no.
(Fun and games with int only removed from answer as superceded by another answer).
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