Check any int type in C #?

I have a function that, among other things, takes an object and a type and converts the object to that type. However, the input object is often double, and the type is some int change (uint, long, etc.). I want this to work if the round number is passed as double (e.g. 4.0), but to throw an exception if the decimal number is specified in (4.3). Is there an even more elegant way to check if a type is some int function?

if (inObject is double && (targetType == typeof (int) || targetType == typeof (uint) || targetType == typeof (long) || targetType == typeof (ulong) || targetType == typeof (short) || targetType == typeof (ushort))) { double input = (double) inObject; if (Math.Truncate(input) != input) throw new ArgumentException("Input was not an integer."); } 

Thanks.

+4
source share
3 answers

This is similar to what you are asking. I tested it only for paired, floating and ints.

  public int GetInt(IConvertible x) { int y = Convert.ToInt32(x); if (Convert.ToDouble(x) != Convert.ToDouble(y)) throw new ArgumentException("Input was not an integer"); return y; } 
+6
source
 int intvalue; if(!Int32.TryParse(inObject.ToString(), out intvalue)) throw InvalidArgumentException("Not rounded number or invalid int...etc"); return intvalue; //this now contains your value as an integer! 
+2
source

You should be able to use a combination of Convert.ToDecimal and x% y, I would think where y = 1 and check the result == 0;

0
source

All Articles