views:

7665

answers:

3

How can you check whether a string is convertible to an int?

Lets say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.

In Javascript we had this parseInt() function, if the string couldn't be parsed, it would get back NaN.

+14  A: 

Int32.TryParse(String, Int32) - http://msdn.microsoft.com/en-us/library/f02979c7.aspx

  bool result = Int32.TryParse(value, out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);         
  }
John Nolan
John, could you fix the spelling mistake on this please. (upvoted though)
Tim Jarvis
Tim, what is the spelling mistake you see?
Jay Bazuzi
I've been editing it, so any mistakes may have been rectified
John Nolan
Excellent, and it returns a value indicating whether the conversion succeeded. Thanks!
Jenko
Cool, the spelling mistake was a lowercase p in the TryParse...fixed now though.
Tim Jarvis
+1 I like the solution, but it could be a little more elegant by running it right into the if statement.
BenAlabaster
+2  A: 

Int.TryParse

keithwarren7
+2  A: 

Could you not make it a little more elegant by running the tryparse right into the if?

Like so:

if (Int32.TryParse(value, out number))     
  Console.WriteLine("Converted '{0}' to {1}.", value, number);
BenAlabaster