Telerik blogs

I was innocently writing a piece of code today and the need arose to check if an input type is a number. Naturally I started looking for such a method inside the .NET classes. After all for a framework which has more than 380,000 methods it will only be logical to have at least one which will do something as basic as this. Guess what? .NET does not ship with such a public method. Whaaaa?

But do stay with me, please! It gets better. Armed with Reflector I decided that even if there is no such public method there must be a private one at least! Thank God there is one. Here is what I found inside the System.Linq.Expressions.Expression:

private static bool IsNumeric(Type type)
{
   
type = GetNonNullableType(type);
   
if (!type.IsEnum)
   
{
       
switch (Type.GetTypeCode(type))
       
{
           
case TypeCode.Char:
           
case TypeCode.SByte:
           
case TypeCode.Byte:
           
case TypeCode.Int16:
           
case TypeCode.UInt16:
           
case TypeCode.Int32:
           
case TypeCode.UInt32:
           
case TypeCode.Int64:
           
case TypeCode.UInt64:
           
case TypeCode.Single:
           
case TypeCode.Double:
               
return true;
       
}
   
}
   
return false;
}

At first glance this code appears totally normal, but if you are more careful you will notice that one TypeCode is missing. Can you guess which?

(scroll down for the answer)

 

 

 

 

 

 

 

 

Answer: TypeCode.Decimal

Why the decimal is not a numeric data type according to Microsoft is completely beyond me. Perhaps some of you guys know?


About the Author

Vladimir Milev

Vladimir Milev is a developer manager.

Comments

Comments are disabled in preview mode.