C# object.Equals Method

This C# example program uses the object.Equals method. It shows object.ReferenceEquals.

Object.Equals. The object.

Equals method compares the contents of objects.

It first checks whether the references are equal, as does object.ReferenceEquals. But then it calls into derived Equals methods to test equality further.

 

 

Example. First, this program uses strings as the arguments to object.Equals. It uses two strings. One is a string literal, and a second is a character that is converted to a string with ToString.

String LiteralToString

 

And: The string literal "a" and the result of ToString are in different memory locations. Their references are thus not equal.

But: The object.Equals method goes one step further. It checks the objects' contents and finds them to be equal.

C# program that uses object.Equals method

using System;

class Program
{
    static void Main()
    {
	// object.Equals compares the contents of two objects.
	// ... They can be in separate memory locations and be equal.
	bool b = object.Equals("a", 'a'.ToString());
	Console.WriteLine(b);

	// object.ReferenceEquals compares the references of two objects.
	// ... They can only be equal if they are in the same memory location.
	b = object.ReferenceEquals("a", 'a'.ToString());
	Console.WriteLine(b);
    }
}

Output

True
False

What about object.ReferenceEquals? With this method, the two strings with equal data are determined to have different references. This is because they are in different memory locations.

Reference: A reference is a simple value that indicates a memory location. It is four or eight bytes.

object.ReferenceEquals

 

Internals. The object.Equals method internally compares the two formal parameters for referential equality. Conceptually it invokes object.ReferenceEquals. Thus Equals is the same as ReferenceEquals except it also calls a virtual Equals method.

Virtual

 

 

Summary. The object.Equals and object.ReferenceEquals method have an important difference in the C# language. Equals actually checks the contents of the objects. ReferenceEquals does not. We demonstrated this difference.

 

Tip: We use object.ReferenceEquals if we want to know if the two variables are the same object in the same memory location.