Friday, May 30, 2008

IsNumeric in C# without try parse or try catch

This is something that has bothered me for a long while now. Why doesn't C# have a IsNumeric(string num) function like VB.NET?
I have used every kind of IsNumeric code you can think of... This is what I started with.

public bool IsNumeric(string s)
{
try
{
Int32.Parse(s);
}
catch
{
return false;
}
return true;
}

But we all no the unspoken rule, NEVER use try, catch for functionality... So I tried this.

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i < ca.Length;i++)
{
if (ca[i] > 57 || ca[i] < 48)
return false;
}
return true;
}

Then I found char.IsNumber: (Why do they have a char.IsNumber, but no string.IsNumeric???)

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i < ca.Length;i++)
{
if (!char.IsNumber(ca[i]))
return false;
}
return true;
}

With the help of some friend (Thanks Dawid), I finally got this. What do you think?

public static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}

No comments: