Press "Enter" to skip to content

C# Tip – See if an object is a numeric datatype

Here is an extension method you can use to check if an object is one of the numeric datatypes.

This comes in handy when using reflection on objects.

using System;
namespace DotNetToolBox
{
    public static class ExtensionMethods
    {
        public static bool IsNumericDatatype(this object obj)
        {
            switch(Type.GetTypeCode(obj.GetType()))
            {
                case TypeCode.Byte:
                case TypeCode.SByte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Single:
                    return true;
                default:
                    return false;
            }
        }
    }
}

 

    Leave a Reply

    Your email address will not be published. Required fields are marked *