Difference is comparison when using equals method or Double Equal to operator

Hi,

 

There are normally two ways to compare 2 objects. One by using == operator and by using the equals method. But these two are not same in the way they implements the comparison.

 

The difference is there in the type of object (reference type or value type)

 

Value Type

For the value types when we use the == operator the comparison is made based on the value of the object. Even with equals method the comparison will be made on value and hence there is no difference.

Reference Type
For reference type the way for working is different. The == operator will compare the reference point of both the objects and return the value.

 But the Equals method will compare by value of the object and will also compare the type of the object.


 For example

StringBuilder Sb1 = new StringBuilder("Vikram");
StringBuilder Sb2 = new StringBuilder("Vikram");

Sb1 == Sb2         //will return False
Sb1.Equals(Sb2) //will return True

But there is an exception to this rule. The exception is made for the string class.

String S1 = "Vikram";
String S2 = "Vikram";

S1 == S2         //will return True
S1.Equals(S2) //will return True

Also remember that the equals operator also compare the type of the method along with value so…

 int i = 0;
 byte b = 0;

 i == b         //will return True
 i.Equals(b) //will return False since the type is different for the type passed

This is why it is always advisable to use the == operator for the reference type and equals method for the value type.

Vikram

4 Comments

  • can u explain overriding GetHashCode() method with Equals()

  • The basic rule is if 2 objects are equal they must have the same hashcode. The reverse does not have to be true-- two objects that have same hashcode do not have to be equal. Knowing this, when you override Equals() you should also make sure GetHashCode() returns a correct value. In most cases it is far simpler to have your object implement IComparable so you don't have to mess with Equal/GetHashCode.

  • that's more interesting
    I tested
    i.Equals(b) //will return TRUE
    but
    b.Equals(i) //will return FALSE

    in net 2.0

  • Hi Vikram,
    I have a word template that has
    Name :
    Ref. No :

    The user enter the name, leaves the Ref.No as empty and he saves the file as .doc file. (example test.doc)

    Now i want to programtically (.NET) open the test.doc and update the Ref. No as 123.

    Can you please help me in achieving this?
    This is quite urgent :(
    Thanks,
    Madhu

Comments have been disabled for this content.