I have a function that, among other things, takes in an object and a Type, and converts the object into that Type. However, the input object is often a double, and the type some variation of int (uint, long, etc.). I want this to work if a round number is passed in as a double (like 4.0), but to throw an exception if a decimal is passed in (4.3). Is there any more elegant way to check if the Type is some sort of int?
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.
This seems to do what you ask. I have only tested it for doubles, floats 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;
}
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