简体   繁体   中英

(object) 0 == (object) 0

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.

Basically, the above is creating two object references, storing them in different locations in memory, then comparing the memory addresses. This will return false every time for that reason.

The only way to compare two objects I know of is check to see if one or both objects are null (if one is null and not the other, they're not equal; I leave it to your implementation to determine if null == null). If neither one is null, you can safely call .equals on the object.

The cast will force boxing, which essentially creates new objects, and then the references are compared. If you want to compare the objects by content instead (using the implemented comparison of the objects that the references point to), you should use the Equals method:

Console.Write(((object)0).Equals((object)0)); // outputs "True"

This may clarify things a little.

object zero = (object)0; return (object.Equals(zero, zero)); // returns true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM