Bilgin's Blog
Crumpler Wee Bee

 


My Crumpler Wee Bee


For my quest of the ideal notebook bag and my review of Crumpler Wee Bee, click

Wee Bee review

Programmers' Blog
Programmer's Blog

Specific hints and tricks for C# programmers.

click for "Programmers' Blog"

IsNumeric in C#
Minimize

Most of us agree that C# is a very convenient tool that few of the old C++ programmers look behind. But there are some missing components such as the good old IsNumeric method of VB6.0.

The thing is, you should write your own IsNumeric function for your own purposes. There are lots of functions you can find on the net. But your purpose of usage is important. For example, by using double.TryParse(...), you will end up considering "NaN" values as "numeric".

I use the below code which I find very appropriate in my applications. This is the improved version of a contribution of a coder, "mluckham" from "The Bumpy Blog". You can read the ongoing debate for IsNumeric solutions here.

public static bool IsNumeric(object input)
{
    if (input == null) return false;

    string text input.ToString();
    bool 
result = false;

    if 
(text.Length > 0)
    {
        
char[] acceptedChars "0123456789,.-'".ToCharArray();
        
result = true; // innocent until proven guilty

        // look for the first non-numeric character in the input string
        
for (int 0i < text.Lengthi++)
        {
            
// if the character is NOT in the list of valid characters, it is not a number
            
if (text.LastIndexOfAny(acceptedChars, i, 1) < 0)
            {
                result 
= false;
                break;
            
}
        }
    }

    
return result;
}
About  |  Affiliate Program  |  Sitemap  |  FAQ's Privacy Statement  |  Terms Of Use
Copyright 2009 by Bilgin Esme