System.Object.ReferenceEquals Method

Determines whether the specified object instances are the same instance.

Syntax

[System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)]
public static bool ReferenceEquals (object objA, object objB)

Parameters

objA
The first object to compare.
objB
The second object to compare.

Returns

true if objA is the same instance as objB or if both are null; otherwise, false.

Remarks

Unlike the object.Equals(object) method and the equality operator, the object.ReferenceEquals(object, object) method cannot be overridden. Because of this, if you want to test two object references for equality and you are unsure about the implementation of the Equals method, you can call the object.ReferenceEquals(object, object) method.

However, the return value of the object.ReferenceEquals(object, object) method may appear to be anomalous in these two scenarios:

  • When comparing value types. If objA and objB are value types, they are boxed before they are passed to the object.ReferenceEquals(object, object) method. This means that if both objA and objB represent the same instance of a value type, the object.ReferenceEquals(object, object) method nevertheless returns false, as the following example shows.

    code reference: System.Object.ReferenceEquals#1

  • When comparing strings. If objA and objB are strings, the object.ReferenceEquals(object, object) method returns true if the string is interned. It does not perform a test for value equality. In the following example, s1 and s2 are equal because they are two instances of a single interned string. However, s3 and s4 are not equal, because although they are have identical string values, that string is not interned.

    code reference: System.Object.ReferenceEquals#2

Example

C# Example

using System;
class MyClass {
   static void Main() {
   object o = null;
   object p = null;
   object q = new Object();
   Console.WriteLine(Object.ReferenceEquals(o, p));
   p = q;
   Console.WriteLine(Object.ReferenceEquals(p, q));
   Console.WriteLine(Object.ReferenceEquals(o, p));
   }
}
   

The output is

True
True
False

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0