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;
	}
}
bool IsStringOrNumericType(Type type)
{
    // Haal het onderliggende type op als het een nullable type is.
    Type underlyingType = Nullable.GetUnderlyingType(type) ?? type;

    // Controleer of het onderliggende type een string of numeriek type is.
    return underlyingType == typeof(string) ||
           underlyingType == typeof(byte) || underlyingType == typeof(sbyte) ||
           underlyingType == typeof(short) || underlyingType == typeof(ushort) ||
           underlyingType == typeof(int) || underlyingType == typeof(uint) ||
           underlyingType == typeof(long) || underlyingType == typeof(ulong) ||
           underlyingType == typeof(float) || underlyingType == typeof(double) ||
           underlyingType == typeof(decimal);
}
27090cookie-checkC# IsNumeric