Convert string to int and test success in C#

Viewed 58544

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

Let's 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.

4 Answers

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);
Related