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