Equals or == operator

During interview also, this can be asked in many different ways like what’s the difference between Equals and ==, why to use Equals for reference types and is there any reference type for which == is preferred and so on.

Equals basically check the contents of the object while comparing equality of two objects but has to be defined in Equals method of that class else it will return false for reference types. On the other hand == checks referential integrity as well along with contents.

e. g. In following example, s and s1 are both string type but s2 is string array with all three s, s1 and s2 having same content as abc.

string s = "abc";
string s1 = "abc";

//s == s1 will return true
//s.Equals(s1) will return true

char[] s2 = ['a','b','c'];
object o = new strung(s2);
//o==s2 will return false
//o.Equals(s2) will return true;

The same behavior is for all primitive data types like int etc. along with any value type. But not with in case of REFERENCE types.
 For reference types equality checking always use Equals until there is any referential integrity need to be checked. The only exception is string type as shown above. Even for reference type equality Equals method need to be overridden in the class. Will discuss about importance of Equals method and why it needs to be overridden will be explained in separate article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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