What is the difference between a.Equals(b) and a == b?


Value Types:
For value types, “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

Reference Types:
For reference types, both works differently :
“==” compares REFERENCE – returns true if and only if both references point to the SAME object.

Equals method compares object by VALUE.

Example:
StringBuilder sb1 = new StringBuilder(”Mahesh”);
StringBuilder sb2 = new StringBuilder(”Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

However

String s1 = “zzz”;
String s2 = “zzz”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True

Why? Does that mean String a Value Type?

No, String IS a Reference Type. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

About these ads

One thought on “What is the difference between a.Equals(b) and a == b?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s