Hello everybody
I am just curious background of some classes and methods in .NET so i just wonder how ReferenceEquals method can understand 2 references belongs to same object or not?
Hello everybody
I am just curious background of some classes and methods in .NET so i just wonder how ReferenceEquals method can understand 2 references belongs to same object or not?
Because 'the same object' means 'same place in memory' and the operation can simply check the 'address' value of a reference.
Not that you can easily get at that value, but then you never need to.
I'd suspect it's checking to see whether the references point to the same object in memory, i.e. is the same address being referenced for both objects.
Because they have the same value. Just like two pointers in an unmanaged app point to the same object if they have the same value.
The reference is basically a 32-bit integer which points to a location in the heap where the object is stored, so ReferenceEquals can simply compare the two integers values and check if they're the same.
Mind you for value types, ReferenceEqual will ALWAYS fail! ValueType overrides the virtual Object.Equals method to compare all member variables in a derived type rather than the reference.
With out knowing the runtime names and types of the member variables, the default implementation of ValueType.Equals relies on the use of reflection and reflection as we all know, is slow. As a general rule of thumb, it’s recommended that you ALWAYS override the ValueType.Equals method when creating your custom value type and you should strongly consider overloading the == and != operators too whilst you’re at it!
ReferenceEqulas
checks the memory location is same or not
class MyClass {
static void Main() {
object o = null;
object p = null;
object q = new Object();
//Here o and p not referring to any location.so result true
Console.WriteLine(Object.ReferenceEquals(o, p));
p = q; // here p's memory location is mapping to q.So both referring to same memory location. so result is true.
Console.WriteLine(Object.ReferenceEquals(p, q));
//Here the p and o are in different memory location so the result is false
Console.WriteLine(Object.ReferenceEquals(o, p));
}
}