Should we use == or Equals() to compare two objects in C#? – C# Programming Example
C# String Methods

Should we use == or Equals() to compare two objects in C#?

As you probably know, to compare two objects with each other, you can use the “==” operator or the Equals() method.
Both exist and do not always do the same thing. I propose to dissect a little behavior between the two solutions.
The purpose of this article is to help you understand and choose the right method.

The == operator is defined by default as the reference comparison operator.
The Equals() method is defined in the System.Object class. All types will inherit it. Some classes will overload the behavior.
We will see this more ready.

== operator or the Equals method

By default, in the Object class, both do the same thing.
The == operator will make it possible to compare the references between two objects.
The Equals() method will do the same thing.

What is important to understand is that in most cases, the Equals() method will be overloaded in classes.
Indeed, Equals() is / must be used to compare the value of the object (its content) and not the reference.

The String class, for example, overloads Equals() to perform a comparison (of characters).

I propose a sample code to better understand:

In this example, I build two strings. For the second one, I use another constructor to avoid the compiler default optimization (otherwise it would have “stored” only one string in your executable and would have assigned the same reference to str1 and str2).

The first call uses == and returns True. This operator is overloaded in the String class (the documentation clearly indicates that the operator will compare the content of the string).
The second call uses Equals() and returns True as well. Equals () compares the content (which is the same for both channels).

In the third call, == is applied to an object of type Object. There is therefore no overload of the operator and the compiler will therefore use the default behavior: compare the references of the two objects obj1 and obj2. This returns False because the references are not the same.

In the fourth call, Equals() is called. This is a virtual method (overloaded in the String class). In fact, .NET will call the String.Equals() method that compares the contents of the string. This will return True as in the second call.

Ok, so how to choose between == or Equals?

When you want to compare references, always use ==.

When you want to compare the content of an object, you will have to use the Equals () method. Compared class should also propose an overload of Equals otherwise you will simply compare the references.

The exception will be the String class since == and Equals have the same result (if the two compared elements are of type String).

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: