I have the following code:
object val1 = 1;
object val2 = 1;
bool result1 = (val1 == val2);//Equals false
bool result2 = val1.Equals(val2); //Equals true
What’s up with that? Is the only way to fix this to go with .Equals() method?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The operator
==is static, not virtual, so the behaviour is determined by the static type and not the runtime type. The default implementation for==on objects of reference type is to compare the references (although types can implement a different behaviour, for examplestring). You have two different objects and they don’t have the same reference so==returns false.The solution, as you point out, is to use Equals. Equals is a virtual method. Since
value1has runtime typeInt32you end up calling Int32.Equals. From .NET Reflector you can see that the implementation of this is as follows:In other words, it checks if the argument is of type
int, and if so casts it and uses the==that is defined forint. This compares the values of the integers.An alternative is to cast your objects to
intand then use==, just as the implementation ofInt32.Equalsdoes.