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 i = 0; i < text.Length; i++)
{
// 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;
}
|