typeof() to check for Numeric values

Moonlight picture Moonlight · Jan 12, 2012 · Viewed 11.9k times · Source

what is the easiest way to check if a typeof() is mathematically usable(numeric).

do i need to use the TryParse method or check it by this:

if (!(DC.DataType == typeof(int) || DC.DataType == typeof(double) || DC.DataType == typeof(long) || DC.DataType == typeof(short) || DC.DataType == typeof(float)))
     {
           MessageBox.Show("Non decimal data cant be calculated");
           return;
     }

if there is a more easy way to achieve this, your free to suggest

Answer

Humberto picture Humberto · Jan 12, 2012

There's nothing much to do, unfortunately. But from C# 3 onwards, you can do something fancier:

public static class NumericTypeExtension
{
    public static bool IsNumeric(this Type dataType)
    {
        if (dataType == null)
            throw new ArgumentNullException("dataType");

        return (dataType == typeof(int)
                || dataType == typeof(double)
                || dataType == typeof(long)
                || dataType == typeof(short)
                || dataType == typeof(float)
                || dataType == typeof(Int16)
                || dataType == typeof(Int32)
                || dataType == typeof(Int64)
                || dataType == typeof(uint)
                || dataType == typeof(UInt16)
                || dataType == typeof(UInt32)
                || dataType == typeof(UInt64)
                || dataType == typeof(sbyte)
                || dataType == typeof(Single)
               );
    }
}

so your original code can be written like this:

if (!DC.DataType.IsNumeric())
{
      MessageBox.Show("Non decimal data cant be calculated");
      return;
}