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:
The problem is as follows:
Int32 i32 = 1;
Int64 i64 = 1;
bool result = i32 == i64;
// outputs TRUE – expected
object o32 = i32;
object o64 = i64;
result = o32 == o64;
// outputs FALSE – expected
// This is expected since it would do a reference comparison BUT
result = i32.Equals(i64);
// 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…