Pages

Wednesday, September 7, 2011

Difference between a.Equals(b) and a==b

Both '.Equals()' and '==' are used for comparison and returns a boolean value(true/false).
Differences are as follows:

1. '==' is used for Value type comparision.
       Ex. int a = 5;
             int b = 5;
             a==b => returns true
             a.Equals(b) => returns true

2. '==' returns true for Value type, only when both the value and the data types are same. .Equals() method returns true if the values are the same. the data type can be different.
      Ex. int a = 5;
            string b = "5";
            a.Equals(b) => Will compile succesfully, and internally the string b will be converted to object types and compare.
            a == b => Will give compilation error.
       By using '==' we cannot compare two objects.
       But .Equals() enables to compare both the objects internally.

3. For Value Type, both '==' and '.Equals()' compare two objects by value.

4. For Reference Type, '==' performs an identity comparison. ie. it will return true only if both references point to the same object. '.Equals()' performs and value comparison.i.e it will return true if the references point to the object that are equivalent.
        Ex. StringBuilder s1 = new StringBuilder("Yes");
              StringBuilder s2 = new StringBuilder("Yes");
              s1 == s2 => returns false.
              s1.Equals(s2) => returns true;

5. Recommendations:
       For Value type - use '=='
       For Reference type - use '.Equals()'

No comments:

Post a Comment