-4

People have been suggesting to use Int32.TryParse but I found out that in case of any string such as "4e",it would give me output 0(i would directly print my input),whereas Int32.Parse would give an Exception. Is there a side to using TryParse which I am not able to see? Any help would be much appreciated

Nuruddin
  • 23
  • 1
  • 6

2 Answers2

2

TryParse and Parse should treat what is a valid number in the same way. The difference is the way they signal that the input was invalid. Parse will throw an exception, while TryParse returns a boolean which you need to manually handle.

if (!int.TryParse(input, out var result))
{
    Console.Write("NOK"); // Don't use result, it will have the default value of 0
}
else
{
    Console.Write($"OK {result}"); // Ok, reuslt has the parsed value of input
}
Titian Cernicova-Dragomir
  • 196,102
  • 20
  • 333
  • 303
1

You can check the boolean return value like this:

  string text1 = "x";
  int num1;
  bool res = int.TryParse(text1, out num1);
  if (res == false)
  {
      // String is not a number.
  }
S.Spieker
  • 6,473
  • 7
  • 45
  • 50