Freigeben über


Object.ReferenceEquals(valueVar, valueVar) will always return false

The ReferenceEquals method is usually used to determine if two objects are the same instance. But you need to be a bit cautious when you use it with Value Types. Consider the following code.

 static void Main(string[] args)
{
    int valueVar = 15;

    if (Object.ReferenceEquals(valueVar, valueVar))
        Console.WriteLine("Reference Equal");
    else
        Console.WriteLine("Reference Not Equal");

    Console.ReadLine();
} // Will always print "Reference Not Equal"

This code will always print "Reference Not Equal" as long as valueVar is a variable of Value Type (that includes struct as well).

If you examine Object.ReferenceEquals it is designed to take two Objects as the input parameters. So when you pass Value Types to it .Net goes ahead and "Boxes" the parameters. Here is the corresponding MSIL that gets generated for the above code

vijay-msil

This "Boxing" results in two different objects being created on the heap that will now be used to do the comparison. You can use SOS to verify this.

vijaysk-sos

So we end up doing a ReferenceEquals between the objects at 0x01d917e0 and 0x01d917ec which obviously will fail(Remember these are now Reference Type objects so the addresses are compared)  and return a false.

To conclude even though Object.ReferenceEquals(valueVar, valueVar) passes the same variable as both the parameters it will always return false.

Bookmark and Share