Is there a way to determine whether or not a given .Net Type is a number? For example: System.UInt32/UInt16/Double are all numbers. I want to avoid a long switc
EDIT: Well, I modified the code below to be more performant and then ran the tests posted by @Hugo against it. The speeds are about on par with @Hugo's IF using the last item in his sequence (Decimal). If however using the first item 'byte' his takes the cake, but clearly order matters when it comes to performance. Although using the code below is easier to write and more consistent on it's cost, it is not, however, maintainable or future proof-able.
Looks like switching from Type.GetTypeCode() to Convert.GetTypeCode() sped up performance drastically, about 25%, VS Enum.Parse() which was like 10 times slower.
I know this post is old but IF using the TypeCode enum method, easiest (and probably the cheapest) would be something like this:
public static bool IsNumericType(this object o)
{
var t = (byte)Convert.GetTypeCode(o);
return t > 4 && t < 16;
}
Given the following enum definition for TypeCode:
public enum TypeCode
{
Empty = 0,
Object = 1,
DBNull = 2,
Boolean = 3,
Char = 4,
SByte = 5,
Byte = 6,
Int16 = 7,
UInt16 = 8,
Int32 = 9,
UInt32 = 10,
Int64 = 11,
UInt64 = 12,
Single = 13,
Double = 14,
Decimal = 15,
DateTime = 16,
String = 18
}
I haven't tested it thoroughly, but for basic C# numeric types, this would seem to cover it. However, as @JonSkeet mentioned, this enum isn't updated for additional types added to .NET down the road.