Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(object) 0 == (object) 0

Tags:

c#

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?

like image 273
jpsimard-nyx Avatar asked Jun 05 '09 19:06

jpsimard-nyx


2 Answers

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))
{
    ...
}
like image 200
Jon Skeet Avatar answered Oct 24 '22 04:10

Jon Skeet


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.

like image 4
n8wrl Avatar answered Oct 24 '22 04:10

n8wrl