Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare boxed objects in C#

Is it possible to compare two objects without knowing their boxed types at compile time? For instance, if I have a object{long} and object{int}, is there a way to know if the boxed values are equal?

My method retrieves two generic objects, and there's no way to know what their inner types are at compile time. Right now, the comparison is made by the following code:

_keyProperties[x].GetValue(entity, null).Equals(keyValues[x])

where, say, _keyProperties[x].GetValue(entity, null) is a object{long} and keyValues[x] is a object{int} (but they can be inverted as well).

I need this because I am building a mock repository for my unit tests, and I have started by including a generic repository implementation as described here. This implementation compares two generic fake-DB keys in its Find method.

like image 635
frapontillo Avatar asked Nov 03 '22 20:11

frapontillo


1 Answers

This might be too slow for your case, but you can use dynamic to do the test as the following code demonstrates:

object obj1 = 1;
object obj2 = 1.0;

if (obj1.Equals(obj2))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No"); // Prints "No" as you'd expect.

if ((dynamic) obj1 == (dynamic) obj2)
    Console.WriteLine("Yes"); // Prints "Yes" because it handles trivial conversions.
else
    Console.WriteLine("No");

Be aware that using dynamic can be slow (although the code generated to support it is cached so at least that part is not performed more than once).

Also it can have some problems if the types are not related - see here for more discussion.

For example, this will throw an exception:

object obj1 = "Hello";
object obj2 = 1.0;

if ((dynamic) obj1 == (dynamic) obj2) // Throws an exception!
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
like image 86
Matthew Watson Avatar answered Nov 09 '22 06:11

Matthew Watson