C# IsNumeric

Date: 2019-10-24
// Preferred way: works with nullable types! (but a null value returns false)
public static bool IsNumeric(object o) => o is byte || o is sbyte || o is ushort || o is uint || o is ulong || o is short || o is int || o is long || o is float || o is double || o is decimal;
// Another way based on a type instead (not preferred in most cases)
public static bool IsNumeric(Type type)
{
	switch (Type.GetTypeCode(type))
	{
		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;
		case TypeCode.Object:
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				return IsNumeric(Nullable.GetUnderlyingType(type));
			}
			return false;
		default:
			return false;
	}
}
27090cookie-checkC# IsNumeric