Checking if an object is a number in C#
You will simply need to do a type check for each of the basic numeric types.
Here's an extension method that should do the job:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
This should cover all numeric types.
Update
It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse
.
string value = "123.3";
double num;
if (!double.TryParse(value, out num))
throw new InvalidOperationException("Value is not a number.");
Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse
/ decimal.TryParse
/ whatever else.
Taken from Scott Hanselman's Blog:
public static bool IsNumeric(object expression)
{
if (expression == null)
return false;
double number;
return Double.TryParse( Convert.ToString( expression
, CultureInfo.InvariantCulture)
, System.Globalization.NumberStyles.Any
, NumberFormatInfo.InvariantInfo
, out number);
}
Take advantage of the IsPrimitive property to make a handy extension method:
public static bool IsNumber(this object obj)
{
if (Equals(obj, null))
{
return false;
}
Type objType = obj.GetType();
objType = Nullable.GetUnderlyingType(objType) ?? objType;
if (objType.IsPrimitive)
{
return objType != typeof(bool) &&
objType != typeof(char) &&
objType != typeof(IntPtr) &&
objType != typeof(UIntPtr);
}
return objType == typeof(decimal);
}
EDIT: Fixed as per comments. The generics were removed since .GetType() boxes value types. Also included fix for nullable values.