0

I am wondering if there is a system function which will tell me if a type represents a numeric value (for a custom TypeConverter). Sure checking for each type known type works ok, but I don't really like it.

        if (destinationType == typeof( int))
            return true;

        if (destinationType == typeof( Int16))
            return true;

        if (destinationType == typeof( Int32))
            return true 
        ...
        if (destinationType == typeof( float))
            return true;
        ...

Thanks.

  • This is a duplicate of a question I definitely remember be asked and answered, but can't seem to find it. – Noldorin Sep 22 '09 at 01:37
  • it get asked alot... it would be a ncie feature that doesn't exist – Matthew Whited Sep 22 '09 at 01:38
  • http://stackoverflow.com/questions/437882/c-equivalent-of-nan-or-isnumeric – xcud Sep 22 '09 at 01:48
  • I figured it might be a reasonably common question and somehow suspected that it wouldn't exist. @xcud - I am looking to see if the type represents a number rather than if a string does. –  Sep 22 '09 at 01:58
  • See also: http://stackoverflow.com/questions/1375026/c-numeric-base-class – Marc Gravell Sep 22 '09 at 06:05

1 Answers1

1

If you look at Linq ExpressionNode (internal class) IsNumeric method, it is basically testing against every type.

if (!IsFloat(type))
{
    return IsInteger(type);
}
return true;

And the two function are testing against the primitive type, like

internal static bool IsInteger(StorageType type)
{
    if ((((type != StorageType.Int16) && (type != StorageType.Int32)) && ((type != StorageType.Int64) && (type != StorageType.UInt16))) && (((type != StorageType.UInt32) && (type != StorageType.UInt64)) && (type != StorageType.SByte)))
    {
        return (type == StorageType.Byte);
    }
    return true;
}

StorageType is a Linq specific class, but you get the idea: just test against every type.

It is the easiest way to know if the value is a numeric type.

Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
  • I figured that it would come down to individual testing of types in the end :( –  Sep 22 '09 at 02:03