I am wondering why in C#
0 == 0 // return true
(object) 0 == (object) 0 // return false
To me it looks like it compares the reference instead of comparing the value of the cast.
This came to me because with Reflection I am getting the default value of ValueType which return an object and when I am comparing it to the current value of my object it returns that both are not the same but have the same value.
Using Equals or ToString work on ValueType object but not with ReferenceType which can be null and therefore do not allow Equals or ToString.
If someone could tell me how can I compare different object that can be of any type, null or with a value since object == object seems to be the wrong way to go. Am oblige to recast my objects into their original type in this case will the ReferenceType always different?
Yes, it's boxing both sides, and comparing the references. Every time you box you create a new object, so the references are different.
Comparing with the Equals
method is the way to go, taking account of nullity. The easiest way is to use the static object.Equals(object, object)
method:
if (object.Equals(x, y))
{
...
}
You're boxing, so the 'cast' actually does create a NEW object for each one. If you're comparing against your object you may have to write your own .Equals implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With