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 object
s, 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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With