Link to home
Start Free TrialLog in
Avatar of mousemat24
mousemat24

asked on

How to check if a value is a integer.

Hi there

Wonder if you can help me?

Im pulling out some information from a SQL table, one of the fields in SQL may contain an integer or char's or alpha numeric.

so

I could have

12   or   testing    or    testing123   or testing 123

How do I check if the value is an integer? So the code will do something if its 12 but do something else if its testing 123 or testing123 or testing.

hope that makes sense?
Mousemat24
Avatar of Priest04
Priest04
Flag of Serbia image

You can use Int32.TryParse method. If it fails, return value is false, and no exception is raised

Goran
Or you can create a custom IsNumeric function, that will loop through all chars and use char method isDigit to  check if it is numeric.

Goran
SOLUTION
Avatar of Yurich
Yurich
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Throwing an exception is the last option, since it is much slower that using int32.TryParse

Goran
goran, are you addressing to me? if yes, where do you see exception throwing?

that's an exception throwing:

throw new Exception( "my exception message" );

but TryParse does indeed looks more elegant and it's less coding.

cheers,
yurich
sorry, it's indeed. disregard first three sentences of my previous post.
Avatar of mousemat24
mousemat24

ASKER

Hi there, you've lost me now, should I use

private bool IsNumber( string str )
{
      try
      {
            int x = Convert.ToInt32( str );
            return true;
      }
      catch
      {
            return false;
      }
}

or not? You say I should use TryParse, can you please send me some code please?

Many thanks for helping me out
Mousemat24
You can use try-catch combo, but more elegant way would be:

private bool IsNumber( string str )
{
      int result = Int32.MinValue;
      return ( Int32.TryParse( str, result ) == null ) ? false : true;
}

Cheers,
Yurich
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks guys for helping out!! :-)
pleasure :)