Search code examples
c#stringtype-conversionintstring-parsing

Best way to check string and convert to int in c#


Please help me to improve my code. The idea is: if string is ok then convert to int

1- it does check just null or blank string

int t=0;
 if(!string.IsNullOrEmpty(textbox1.text.trim())
     t= int.Parse(textbox1.text.trim());

2-

if(int.tryparse(textbox1.text.trim(), out t)      
   t=int.Parse(textbox1.text.trim());

or shortif

 return string.IsNullOrEmpty(textbox1.text.trim()) ? 0 :  int.Parse(textbox1.text.trim());

is there other better way?


Solution

  • The correct way to get user input and convert it to integers is through the Int32.TryParse method. This method has the advantage to not throw a costly exception if the input is wrong (like Parse or Convert.ToInt32) but returns true or false allowing you to display a meaningful error message to your user.

    int t;
    if(Int32.TryParse(textbox1.Text, out t)
    {
      // t has ben set with the integer converted
      // add here the code that uses the t variable
    }
    else
    {
      // textbox1.Text doesn't contain a valid integer
      // Add here a message to your users about the wrong input....
      // (if needed)
    }
    

    Notice that textbox1.Text is never null so you don't need to explicitly check for it. Of couse I assume that this textbox1 is a TextBox control defined in your InitializeComponent call and thus is not null by itself.