Use TryParse to parse values entered by the user in C#

The example Parse user-entered values in C# explains how you can use a try catch block to protect against errors when parsing values entered by the user. For example, if the user types "ten" in a text box where you expect an integer, a try catch block can prevent the program from crashing.

Another approach is to use a data type's TryParse method. Data types such as int, float, bool, and decimal all provide a TryParse method that takes as parameters the text to parse and an output variable in which to place the result. The method sets the output variable to a default value (0 for the numeric data types) if it cannot parse the text. The method returns true if it could parse the text and false if it could not.

The program uses the following code to parse a double value and a decimal value.

// Parse the values.
private void btnParse_Click(object sender, EventArgs e)
{
double value;
if (!double.TryParse(txtNumber.Text, out value)) value = -1;

decimal currency;
if (!decimal.TryParse(txtNumber.Text, NumberStyles.Any, null, out currency)) currency = -1;

MessageBox.Show("Value: " + value.ToString() +
"\nCurrency: " + currency.ToString());
}

The code first creates a double variable and uses TryParse to parse its value. If TryParse cannot parse the value, the code sets the value to -1. (TryParse sets it to 0 if it cannot parse the text.)

Next the code parses a decimal value. It uses NumberStyles.Any and a null format provider to indicate that TryParse should be able to parse currency values in addition to other decimal formats.

The code finishes by displaying the results.

In the picture, the program failed to parse $1,234.56 as a double but succeeded in parsing it as a currency value.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.