Tell me, I have a TextBox, in it I want to enter a password and transfer values ​​to a variable of type int ... did I make the code correctly?

int pass; int.TryParse(textPassword.Text, out pass); 

* textPassword = This is a TextBox

  • I think it's better to use Convert.ToInt32() - Specter
  • one
    Actually, no, in the case of the Convert class, you still need to handle exceptions. Both have the right to life, but IMHO is better to use tools that help avoid exceptions. In this case, if you just need to convert the value without figuring out the reasons why the conversion may fall - it is better to use TryParse, if you want the method to throw an exception and handle some situation (specific to the type of exception) - then use the methods of the class Convert - Eugene Cheverda
  • if it is necessary for the value to be numeric, and the user has entered something else, then he should be notified about it anyway, and working out the exception thrown by the Convert `just for that! - Specter
  • And in this case, I have the error "The input string had the wrong format." If you use Convet.ToInt32 (); - Angus123 '11 : 29

1 answer 1

Code approx. Application itself

 int.TryParse(string s, out int result) 

correct.

  • facepalm , thanks remember. - Angus123
  • Usually, TryParse is used in conjunction with the return value from the function in order to correctly handle situations when the conversion drops. - Eugene Cheverda