Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for any int type in C#?

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.

like image 954
Eric W Avatar asked Mar 01 '23 04:03

Eric W


1 Answers

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;
    }
like image 115
Amy B Avatar answered Mar 12 '23 06:03

Amy B