When you use the standard Microsoft .NET TextBox or MaskedTextBox controls for web or Windows forms, the data returns to your program as a string. If your application requires numeric data, you need to convert the string to a numeric data type in your program.
The problem is that a user may have entered invalid data in a numeric field, such as adding alphabetic characters along with digits.
For each of the numeric data types (integer, decimal, etc.), .NET provides two methods you can use to parse a string field into a numeric field. .NET 1.0 introduced the first method, Parse. The second method, TryParse, arrived with .NET 2.0.
To learn these methods, you can examine or run the program Figure 1 shows. This is a simple Console program that prompts for a decimal amount, then for a code to select which method to use.
At first glance, the Parse method looks like it is the simpler method to use. In most cases, you only need to specify the string parameter that you are parsing and assign the result to the numeric field: d = Decimal.Parse(s)
The problem with Parse is that if there are invalid characters in the string, an exception is thrown. If you don’t enclose the Parse method in a Try/Catch block, as shown in the example, the program errors out. You can see the error that occurs by commenting out the Try, Catch, and End Try statements and then running the program with an invalid numeric entry.
The TryParse method takes the string to parse and the resulting field as parameters. It returns a boolean value to indicate the success or failure of the parse operation: b = Decimal.TryParse(s, d)
Unlike the Parse method, if the string contains invalid numeric characters, it doesn’t throw an exception, so you don’t need to enclose TryParse in a Try/Catch block.
Most .NET resources suggest that it is better for performance to avoid unnecessary Try/Catch blocks. Based on that, you may want to consider using TryParse in preference to Parse to get data from strings into numeric fields.
Craig Pelkie (craig@web400.com) has worked as a programmer with IBM midrange computers for many years. He has also written and lectured extensively on AS/400 and System i technologies, including client/server programming, Client Access, Java, WebSphere, .NET applications for the System i, and web development.