Quiz about Object.Equals()
I posted a quiz about C# equality here. It focused on equality via operator== and had questions like “what does this evaluate to: ((float) (int) x == (int) (float) x)”.
The key takeaway from the quiz was that after you account for reference vs. value equality, temporary objects, and conversions, it’s not always obvious when two things are equal or not. (As of the time of this writing, 3/12/05, I haven’t gotten one correct answer to that quiz) It turns out that operator== would return false when one may innocently expect it to return true.
The CLR has Object.Equals() to try and simplify this. Collection classes that store System.Object instances are encouraged to use Object.Equals instead of operator== to avoid the pitfalls demonstrated in the last quiz.
So here’s a followup quiz. These are the same questions in the last quiz, but using Object.Equals() instead of operator==.
Given that x is a local C# variable of type ‘int, are the following C# expressions true or false? (Assume an unchecked context)
- ( x ).Equals( x )
- ( (object) x ).Equals( (object) x )
- ( (System.Object) x ).Equals( (System.Object) x )
- ( (int) (object) x ).Equals( (int) (object) x )
- ( (float) x ).Equals( (float) x )
- ( (int) x ).Equals( (int) x )
- ( (int) x ).Equals( (float) x )
- ( (float) (int) x ).Equals( (int) (float) x )
- ( (System.Int32) x ).Equals( (System.Int32) x )
- ( x.ToString() ).Equals( x.ToString() )
- ( (object) x.ToString() ).Equals( (object) x.ToString() )
I’ll post the answers later.
(Update: What I thought was a potential CLR bug appears to be a C# compiler difference between the V1.0 and V2.0 CLR. Following up... )
Comments
- Anonymous
March 12, 2005
The comment has been removed - Anonymous
March 13, 2005
Austin - You're very close! I think you have 1 wrong answer, and 1 correct answer but with the wrong reasoning. I'll post the answers in a bit. - Anonymous
March 23, 2005
In the above change #7 and #8
#7 False but the reason is that that after boxing (float) x will preserve it's type (i.e. "boxed float") and therefore Equal will return false
#8 False. The explanation is reverse of #7