Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof() to check for Numeric values

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

like image 603
Moonlight Avatar asked Jan 12 '12 13:01

Moonlight


1 Answers

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;
}
like image 56
Humberto Avatar answered Oct 13 '22 21:10

Humberto