.NET Tip: Converting Strings to Numbers

.NET Tip: Converting Strings to Numbers

First, take a look at the Convert class. The Convert class offers methods to convert to and from every base data type, but for the purpose of this tip I'm only going to use the Convert.ToInt32() method. The method accepts a string parameter and returns an integer. If you pass in a string containing a valid integer value, the method returns an integer as expected. If you pass in a null value, the value 0 is returned. If you pass in a string that cannot be converted to an integer, an exception is raised. Here are examples of calls to the Convert.ToInt32() method with the comment indicating the result.

int x; 

x = Convert.ToInt32("123");    // x = 123
x = Convert.ToInt32(null);     // x = 0
x = Convert.ToInt32("abc");    // System.FormatException

Another option is to use the Parse() method available on the numeric base data types. For my purpose, I'm going to stick with int.Parse() for my examples. As with Convert.ToInt32(), if you pass in a string containing a valid integer value, the method returns an integer as expected. Passing in null or a string that cannot be converted, however, results in System.ArgumentNullException and System.FormatException exceptions respectively. Here is how you would use int.Parse().

int x; 

x = int.Parse("123");    // x = 123
x = int.Parse(null);     // System.ArgumentNullException
x = int.Parse("abc");    // System.FormatException

Until very recently I almost always used various flavors of Convert to convert strings to numbers. I avoided using Parse() mainly because of how null values are handled. In my application, having the result be 0 instead of an exception was preferred. I recently came across the TryParse() method on numberic base data types and have begun using it. The difference with TryParse() is that it takes the variable to store the result of the parsing as an out parameter and returns true or false to indicate whether the parsing was successful. No exceptions are raised for null values or values that cannot be converted. For most applications, that is how I prefer to have those conditions handled. Below are examples of using TryParse().

int x;
bool b;

b = int.TryParse("123", out x);    // x = 123, b = true
b = int.TryParse(null, out x);     // x = 0,   b = false
b = int.TryParse("abc", out x);    // x = 0,   b = false

Depending upon your application, one of these methods of converting strings to numbers may have an advantage over the others. I just want to make you aware of how the different options behave so you are able to make good decisions when designing your application.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds