开发者

How to compare two boxed numbers for equality in .NET?

Suppose I have the following, completely pointless code:

object val1 = 1;开发者_StackOverflow
object val2 = 1l;

The below will return false, because the two boxed objects aren't the same, as objects they have different types:

val1 == val2

The same applies for:

val1.Equals(val2)

Or:

Object.Equals(val1, val2)

What is the easiest way to compare these in the same way that the following would, considering I don't know the types at runtime (and hence cannot cast):

1 == 1l;

In other words, how do I get a value based comparison on two boxed numbers?


Try using the dynamic keyword. It will resolve the objects to your value types so that you can use the == operator and compare the true values:

(dynamic)val1 == (dynamic)val2


If it's a specific type of object, you can use the .Equals() method to check equality - either one of the standard .Net types which supports it or by adding it to your own objects.

Failing that, you can cast them to a known type if you know in advance what it will be

Good points from cdhowie so...

I may be missing something but you know they're numbers from the title of the question/tags - unless you have some custom types for storing numbers, can't you simply cast everything to Long (or ULong if +ve only) and then compare?


If you don't know the type then I think you'll have to do some reflection to figure out what means of comparing data is required.


I took a look at System.ValueType.Equals(obj, obj)

However, using Reflector you can see that this method specifically returns false if the types don't match.

You could try extend your own method, say, object.ValueEquals(obj, obj), using the code from Reflector and eliminating that check.

Worth a shot i'd say.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜