Sunday, September 27, 2015

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


For value types: “==” and Equals() works same way : Compare two objects by VALUE
Example:

    int i = 5;
    int k= 5;
    Here “==” and Equals() is as:
    i == k >> True
    i.Equals(k) >> True

 For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:

    StringBuilder objSb1 = new StringBuilder("Elias");
    StringBuilder objSb2 = new StringBuilder("Elias");

    Here “==” and Equals() is as:
    objSb1 == objSb2 >> False
    objSb1.Equals(objSb2) >> True

But now look at following issue:

    string s1 = "Elias";
    string s2 = "Elias";

    Here “==” and Equals() is as:
    In above case the results will be,
    s1 == s2 >> True
    s1.Equals(s2) >> True

String is actually reference type: its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:
    int i = 0;
    byte b = 0;

    Here “==” and Equals() is as:
    i == b >> True
    i.Equals(b) >> False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation:
For value types: use “==”
For reference types: use Equals method.

No comments: