Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two variables when the value is the same but the type is different (e.g. Int16, Int32, Int64)

Tags:

c#

.net

I need to compare two variables to find if they are the same. These variables are cast as "object" and could be assigned any .NET type.

The problem I am encountering is if they are both numbers. In situations where they have the same value (e.g. they are both -1) but have different types (e.g. one is Int32, the other is Int64) then object.Equals returns false.

Is there a reasonably generic way to compare values that will ignore the type of the variable and only look at the number value?

like image 359
James Newton-King Avatar asked Nov 04 '22 23:11

James Newton-King


1 Answers

Assuming the types are boxed integers, so you can't simply == them, you might want to use Convert.ToInt64 to convert all the values to longs and then compare them using ==. You'll need extra logic if you want to support UInt64s though.

like image 65
Trillian Avatar answered Nov 13 '22 08:11

Trillian