Comparing different type with Double Equal operator and Equal method
Posted on 2/2/2010 4:04:18 PM
in #ASP.NET 2.X
Hi,/P>
/o:p>/P>
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./P>
/o:p>/P>
The difference is there in the type of object (reference type or value type)/P>
/o:p>/P>
Value Type /P>
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.
/P>
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./P>
/SPAN>But the Equals method will compare by value of the object and will also compare the type of the object./P>
/SPAN>For example /P>
StringBuilder Sb1 = new StringBuilder("Vikram"); StringBuilder Sb2 = new StringBuilder("Vikram"); /P>
Sb1 == Sb2 /SPAN>////will return False Sb1.Equals(Sb2) ////will return True/P>
But there is an exception to this rule. The exception is made for the string class./P>
String S1 = "Vikram"; String S2 = "Vikram"; /P>
S1 == S2 /SPAN>////will return True S1.Equals(S2) ////will return True/P>
Also remember that the equals operator also compare the type of the method along with value so…/P>
/SPAN>int i = 0; byte b = 0; /P>
i == b /SPAN>////will return True i.Equals(b) ////will return False since the type is different for the type passed/P>
This is why it is always advisable to use the == operator for the reference type and equals method for the value type.
Vikram/P>
|
Posted on 5/23/2010 6:13:46 PM
Hi vikram,
that was a very good explanation.
/p>
I is concluded that "This is why it is always advisable to use the == operator for the reference type and equals method for the value type."
/p>
but it should be other way around right?
/p>
that is"it is always advisable to use the == operator for the value type and equals method for the reference type."
/p>
Regards,
Radhiga
/p>
|