c# isNumeric() or similar

Associate
Joined
17 Oct 2002
Posts
312
Location
herts
hi

how would i check to see if text entered into a text box is numeric before converting to an int type?
also how can i loop through text boxes to do this rather than doing each one seperately.

foreach txtbox
if textbox1.text == "" or not isnumeric
then textbox1.focus
exit loop
loop

i hope you understand what im trying to say

cheers

matt
 
EDIT: Do what Inquisitor said instead!


Don't think it exists in c# but you could try something like this:

Code:
void TextBoxLoop()
{
   List<TextBox> txtBoxList = new List<TextBox>();

   foreach (TextBox txtBox in txtBoxList)
   {
      if (!IsNumeric(txtBox.Text))
      {
         txtBox.Focus();
         break;
      }
   }
}

bool IsNumeric(string str)
{
   try
   {
      int str2int = int.Parse(str);
      return true;
   }
   catch
   {
      return false;
   }
}

....i'm sure there will be some false syntax in there somewhere, but you get the point.
 
Last edited:
Don't think it exists in c# but you could try something like this:

Code:
bool IsNumeric (string str)
{
   try
   {
      int str2int = (int)str;
      return true;
   }
   catch
   {
      return false;
   }
}

....i'm sure there will be some false syntax in there somewhere, but you get the point.

You really shouldn't do this; exceptions should only occur in exceptional circumstances, hence the name.

Besides, it won't work anyway as you can't cast strings.

What you need to do instead is something like this:

Code:
string foo = string.Empty;
int bar;
bool isNumeric = int.TryParse(foo, out bar);
if (isNumeric)
{
    // We have an integer.
}
else
{
    // We don't have an integer.
}
 
Another variation...

Code:
bool IsStringNumeric(string myString) {
  for (int i = 0; i < myString.Length; i++)
     if (!Char.IsDigit(myString[i]))
        return false
  return true
}

TryParse/Parse aren't exactly high performance for a simple test like this. Not that I'm advocating premature optimisation or anything.
 
In Java I'd just do

Code:
if ( textString.matches("\d+") ) doStuff();

in C# I think that might be:

Code:
if ( Regex.IsMatch(textString, "\d+") ) doStuff();

However, I can't find the API and cobbled that off the msdn forums. (I find it slightly shocking as to how hard it is to find a specific class in the .NET API, typing Java 6 Regex API into google gets me what I want immediately, oh well).

Since I cant see the API I dont know if the IsMatch matches the full string by default, if not then you need to do:

Code:
if ( Regex.IsMatch(textString, "^\d+$") ) doStuff();

You may also need to do an escape on the digits character class, ie "\\d+". Can't comment on performance here either sorry.

Edit:

IOW if you want a method:

Code:
bool IsNumeric(string s) {
return Regex.IsMatch(s, "\d+");
}

P.S If Inq's way uses a method on the int class then theres really no need to re-invent the wheel by using regex, just use the api.
 
Last edited:
You really shouldn't do this; exceptions should only occur in exceptional circumstances, hence the name.

Besides, it won't work anyway as you can't cast strings.

What you need to do instead is something like this:

Code:
string foo = string.Empty;
int bar;
bool isNumeric = int.TryParse(foo, out bar);
if (isNumeric)
{
    // We have an integer.
}
else
{
    // We don't have an integer.
}
You realise TryX does try{}catch(){} it's variant? Hence the prefix Try.

So try parse would be:
Code:
bool TryParse (str in, int out) {
  try { out = this.Parse(in); return true }
  catch (Exception e) { return false }
}
(syntax may be off..)
Exceptions are to be *thrown* in exceptional circumstances, but can be caught for any.
 
Dj_Jestar said:
Exceptions are to be *thrown* in exceptional circumstances, but can be caught for any.

You're still knowingly causing them to be thrown in unexceptional circumstances, though, which is arguably the same thing.

Besides, I think it's largely a question of semantics to be honest. It's preferable to use a method to test for condition than seeing whether an exception is thrown in order to determine the outcome, even if that method uses the same mechanism internally.

Though I suppose if the mechanism it uses is implicit in its name then that might not be so relevant, I dunno.
 
You realise TryX does try{}catch(){} it's variant? Hence the prefix Try.

So try parse would be:
Code:
bool TryParse (str in, int out) {
  try { out = this.Parse(in); return true }
  catch (Exception e) { return false }
}
(syntax may be off..)
Exceptions are to be *thrown* in exceptional circumstances, but can be caught for any.

Not true. Use Reflector to see how it is implemented. You'll see that Parse() actually wraps around TryParse(). So the inverse of what you are saying is true.

I use the Try pattern in my designs all the time and I certainly would never dream of implementing a Try*() that just catches the exceptions but returns a boolean instead. It is completely pointless and defeats the purpose of the Try pattern.
 
However, I can't find the API and cobbled that off the msdn forums. (I find it slightly shocking as to how hard it is to find a specific class in the .NET API, typing Java 6 Regex API into google gets me what I want immediately, oh well).

Google has had terrible indexing of the MSDN Library for years. Not really a surprise considering they are arch rivals.

Easiest thing to do is goto the msdn.microsoft.com/library directly and do your search from there. Alternatively download the MSDN Library and install onto your PC.
 
Google has had terrible indexing of the MSDN Library for years. Not really a surprise considering they are arch rivals.

Easiest thing to do is goto the msdn.microsoft.com/library directly and do your search from there. Alternatively download the MSDN Library and install onto your PC.

Thanks, good for future reference!
 
Not true. Use Reflector to see how it is implemented. You'll see that Parse() actually wraps around TryParse(). So the inverse of what you are saying is true.

I use the Try pattern in my designs all the time and I certainly would never dream of implementing a Try*() that just catches the exceptions but returns a boolean instead. It is completely pointless and defeats the purpose of the Try pattern.
Fair do's. I don't use .NET much, but other platforms do what I described. Try is after all the first keyword in a try catch. :) It's also not uncommon to see catch (FileNotFoundException e) { System.out.println('File could not be found/read'); doSomethingElse(); } in many app's.

It's a myth about staying away from exceptions. They can be used in functionality, otherwise we wouldn't have try/catch.
 
The Try*() pattern uses a word from exception handling yes but that is where the similarities end :) I would be surprised also if the Java framework implements its Try*() patterns by just wrapping the exceptions and returning booleans.
 
"isNumeric" is a misleading method name, "isInt" would be more accurate as none of the posted solutions will catch floating point numbers. :)

OR..

Do you actually want to recognise floating point numbers?
 
It's a myth about staying away from exceptions. They can be used in functionality, otherwise we wouldn't have try/catch.
But i think other posters were correct when they said its a bad design, plus exceptions (in dotnet anyways) are very expencive. You wouldnt want a fairly common feature, like tryparse, to be raising exceptions.
 
But i think other posters were correct when they said its a bad design, plus exceptions (in dotnet anyways) are very expencive. You wouldnt want a fairly common feature, like tryparse, to be raising exceptions.

While using exceptions in unexceptional circumstances is semantically incorrect (and so shouldn't be done), it's not true that exceptions are as expensive as they're often made out to be. See Jon Skeet's article on it (and follow-up article).
 
While using exceptions in unexceptional circumstances is semantically incorrect (and so shouldn't be done), it's not true that exceptions are as expensive as they're often made out to be. See Jon Skeet's article on it (and follow-up article).
There's sometimes a conflict. I've seen (paraphrased to fit the subject of this thread) code such as:
Code:
if (isNumeric(aNum)) {
  throw new NumberFormatException('Number is not a vaild number!');
}
doSomethingWith(aNum);
when you could (and should!) just go ahead with:
Code:
doSomethingWith(Integer.Parse(aNum));
Still get the same result - a NumberFormatException (or whatever it's called in .NET) is thrown.

Exceptions are there to provide a get-out of the current flow. If you have a big number crunching sequence, but that sequence must stop when you get a spanner in the works, exceptions are fit for this purpose. It really is a myth to avoid them. Likewise for catching.
Code:
FileReader file;
try {
  file = new FileReader(aFilePath);
} catch (FileNotFoundException e) {
  /*
   * the original file path does not exist, so try with the other..
   * If this dies, let the exception bubble to our superior
   */
  file = new FileReader(anotherFilePath);
}
 
Last edited:
There's sometimes a conflict. I've seen (paraphrased to fit the subject of this thread) code such as:
Code:
if (isNumeric(aNum)) {
  throw new NumberFormatException('Number is not a vaild number!');
}
doSomethingWith(aNum);
when you could (and should!) just go ahead with:
Code:
doSomethingWith(Integer.Parse(aNum));
Still get the same result - a NumberFormatException (or whatever it's called in .NET) is thrown.

Absolutely spot on.

Dj_Jestar said:
Exceptions are there to provide a get-out of the current flow. If you have a big number crunching sequence, but that sequence must stop when you get a spanner in the works, exceptions are fit for this purpose. It really is a myth to avoid them. Likewise for catching.

You're right, but what I'm saying is that exceptions should not be used just as logical flow control mechanisms; rather they should be used when problems occur.

Dj_Jestar said:
Code:
FileReader file;
try {
  file = new FileReader(aFilePath);
} catch (FileNotFoundException e) {
  /*
   * the original file path does not exist, so try with the other..
   * If this dies, let the exception bubble to our superior
   */
  file = new FileReader(anotherFilePath);
}

If you're expecting the first file to be found then this code is fine. However, if you don't know/care, then you should really check beforehand and then decide which to open, throwing an exception as appropriate if neither exist. Besides, if neither file is found in this example, then the exception thrown only indicates that one of the files couldn't be opened.

I think this argument's starting to descend into semantic pedantry really :p
 
Last edited:
Back
Top Bottom