views:

4780

answers:

3

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.

+3  A: 

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;
    }
David B
A: 

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

PolyglotProgrammer
I think you'll find that's not true...?2.4 % 10.39999999999999991
PolyglotProgrammer
A: 
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!
Ricardo Villamil