Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Try and Ye Shall Succeed : Page 2

Converting data from text to numeric types gets simpler in the .NET 2.0 Framework with the TryParse method.

Converting Data in .NET
As for seeking professional help, it has always seemed to me that converting data from text to numeric values, in the .NET Framework, was always just too much trouble. Sure, the Convert class adds a bunch of methods that handle all the conversions for you, but if your conversion fails, these methods raise an exception.

Let's start with a simple case: Imagine that you've got an application in which the user enters an integer into a text box, and you need to convert it to an integer for storage in a local variable. The following code uses the Int32.Parse method to perform the conversion:

' VB Try Dim value As Integer = Integer.Parse(TextBox1.Text) ' Do something with value. Catch ex As FormatException MessageBox.Show( "Please enter an integer.") End Try // C# try { int value = int.Parse(textBox1.Text); // Do something with value. } catch (FormatException) { MessageBox.Show( "Please enter an integer.") }

Although this code isn't terribly onerous, it does require you to trap an exception, and in the case in which the user enters an invalid value, you pay the price for handling the exception. (If you haven't noticed, throwing an exception is quite slow, and although it's not a real problem when the user interface is involved, in data manipulation code, you really see the difference in speed!)

What if you want to allow the user to enter a currency value? That's handled by the framework, as well, using another overloaded version of the Parse method:

' VB ' Import the System.Globalization namespace: Try Dim value As Single = Single.Parse( _ TextBox1.Text, _ NumberStyles.AllowCurrencySymbol Or _ NumberStyles.AllowDecimalPoint) ' Do something with value. Catch ex As FormatException MessageBox.Show( _ "Please enter a currency value.") End Try // C# // Import the System.Globalization namespace: try { float value = float.Parse(textBox1.Text, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint); // Do something with value. } catch (FormatException) { MessageBox.Show( "Please enter a currency value."); }

That's not so bad either, right? But it still requires an exception handler. In the .NET Framework 2.0, it's easier. Instead of handling an exception, you can call the TryParse method instead. (I love the name—so optimistic: "I'm going to TRY REALLY HARD to perform this conversion for you. I might fail, but I'm GOING TO TRY." I need to sleep more.) The TryParse method, available on all the value types (from Boolean to Uint64), makes it easy to parse text into values. It accepts the value to be parsed, and a by reference/out parameter into which it places the parsed text. The method returns True if it succeeded and False otherwise. No exceptions, no muss, no fuss. (For more information on the new method, check out the help topic titled "Parse vs. TryParse Application Sample" in the MSDN documentation.)

The previous example, coded using the TryParse method, might look like this:

' VB Dim value As Single If Not Single.TryParse(TextBox1.Text, _ NumberStyles.AllowCurrencySymbol Or _ NumberStyles.AllowDecimalPoint, _ Nothing, value) Then MessageBox.Show( _ "Please enter a currency value.") End If // C# // Import the System.Globalization namespace: float value; if (!float.TryParse(textBox1.Text, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, null, out value)) { MessageBox.Show( "Please enter a currency value."); }

Note that the TryParse method doesn't include an overloaded version that allows you to specify number formatting without also specifying an IFormatProvider instance-the sample code passed Nothing/null for the IFormatProvider parameter. (You can use an IFormatProvider instance to control the formatting of the parsed value. See the MSDN documentation for more information.)

I really like TryParse, and it's easy to miss. If you find yourself needing to parse data that comes to you from user input, it's a great tool. It's even more useful when you need to programmatically manipulate large amounts of data-not having to handle slow exceptions when things go wrong can save you a lot of time.

As with remodeling projects, finding the professional to do the work for you pays off when parsing text. (Yes, a very thin analogy. But I try!) Unless you're way smarter than me, find someone who knows what they're doing when it comes time to pick out the projector and screen. I'll report in on the success of the venture next time, once it's all up and running.

Ken Getz is a senior consultant with MCW Technologies and splits his time between programming, writing, and training. He specializes in tools and applications written in Visual Studio .NET and Visual Basic. Ken is the author of the highly rated .Finalize() column in CoDe Magazine. He is also the co-author of several best-selling books, including Access 2002 Developer's Handbooks with Paul Litwin and Mike Gunderloy, Visual Basic Language Developer's Handbook with Mike Gilbert, and VBA Developer's Handbook with Mike Gilbert (Sybex). He co-wrote several training courses for Application Developer's Training Company, including VB.NET, ASP.NET, Access 2000 and 97, Visual Basic 6, and Visual Basic 5 seminars. He has also recorded video training for AppDev covering VB.NET, ASP.NET, VB6, Access 2000, and Access 97. Ken is a frequent speaker at technical conferences and has spoken often at Microsoft's Tech-Ed conference. Ken's also a technical editor for Access-VB-SQL Advisor magazine and a columnist for Informant Publications' asp.netPRO magazine..
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date