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… )