System.Object.Equals Method

Determines whether the specified object instances are considered equal.

Syntax

public static bool Equals (object objA, object objB)

Parameters

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

Returns

true if the objects are considered equal; otherwise, false. If both objA and objB are null, the method returns true.

Remarks

The static object.Equals(object, object) method indicates whether two objects, objA and objB, are equal. It also enables you to test objects whose value is null for equality. It compares objA and objB for equality as follows:

  • It determines whether the two objects represent the same object reference. If they do, the method returns true. This test is equivalent to calling the object.ReferenceEquals(object, object) method. In addition, if both objA and objB are null, the method returns true.

  • It determines whether either objA or objB is null. If so, it returns false.

  • If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the object.Equals(object) method, this override is called.

Example

The following example demonstrates the object.Equals(object) method.

C# Example

using System;

public class MyClass {
   public static void Main() {
   string s1 = "Tom";
   string s2 = "Carol";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = "Tom";
   s2 = "Tom";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = "Tom";
   Console.WriteLine("Object.Equals(null, \"{1}\") => {2}",
       s1, s2, Object.Equals(s1, s2));

   s1 = "Carol";
   s2 = null;
   Console.WriteLine("Object.Equals(\"{0}\", null) => {2}", 
       s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = null;
   Console.WriteLine("Object.Equals(null, null) => {2}", 
       s1, s2, Object.Equals(s1, s2));
   }
}
   

The output is

Object.Equals("Tom", "Carol") => False
Object.Equals("Tom", "Tom") => True
Object.Equals(null, "Tom") => False
Object.Equals("Carol", null) => False
Object.Equals(null, null) => True

Requirements

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