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
            Asked
            
        
        
            Active
            
        
            Viewed 772 times
        
    2 Answers
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
        
- 230,986
- 31
- 415
- 357
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
        
- 7,005
- 8
- 44
- 50
