How to check if IsNumeric?

If you need to check if something is a number, in C# doesn’t exist a function for that. That I’ve created the following code.

public bool IsNumeric(object Expression)
{
    if (Expression == null || Expression is DateTime)
        return false;

    if (Expression is Int16 || Expression is Int32 || 
        Expression is Int64 || Expression is Decimal || 
        Expression is Single || Expression is Double ||
        Expression is Boolean)
        return true;

    try
    {
        if (Expression is string)
            Double.Parse(Expression as string);
        else
            Double.Parse(Expression.ToString());
        return true;
    }
    catch { } // just dismiss errors but return false
    return false;
}


Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.