Q: When is 1 not equal to 1?

A: When you’re using .Net and boxed value types.


“What?? No, you’re wrong.  Its not possible – you must be using the framework incorrectly.”


That’s what I would have said, but I’m not so sure after having to fix our little problem at work this morning.


We have a function that takes 2 object parameters:
public bool myFunction(object left, object right))
Which tries a whole bunch of things and if non of them works, it returns:
left.Equals(right);


The problem is as follows:


Int32 i32 = 1;
Int64 i64 = 1;
bool result = i32 == i64;
System.Diagnostics.Debug.WriteLine(result.ToString());
// outputs TRUE – expected
object o32 = i32;
object o64 = i64;
result = o32 == o64;
System.Diagnostics.Debug.WriteLine(result.ToString());
// outputs FALSE – expected
// This is expected since it would do a reference comparison BUT
result = i32.Equals(i64);
System.Diagnostics.Debug.WriteLine(result.ToString());
// outputs FALSE – not expected
// It does it because i64’s type is not the same as i32’s type
// The same goes for result = i64.Equals(i32).
// And also for result = o32.Equals(o64);

Now the question remains – how on earth do I get this code to work?  Currently I’ve written my own IsEqualTo(object left, object right) function which finds out which of the numeric types each object is and casts the left and right parameters to the most suitable types before it does the comparrison so that it works correctly… I’ll upload a ZIP with a sample solution in it that demonstrates the solution, but if you know of a better way to write the code (keeping in mind that it needs to be generic enough to handle any type variables that are passed in), please let me know…

One thought on “Q: When is 1 not equal to 1?

  1. It’s difficult to see from your code snippet, where the data comes from. You are not going to be able to do the comparisons for value types "generically" without doing the cast. If the types are known at compile time, I would suggest possibly creating a whole bunch of overloads of the method, with the object-object comparison as a last resort.

Leave a Reply

Your email address will not be published. Required fields are marked *