Base Data Types
  Sort an array
  Format a string
  Parse datatypes
  Compare references
  Compare object values
  Use mathematical functions

Get URL for this page

How Do I...Parse datatypes?

Moving information from one data type to another is essential when dealing with data. Parsing information from a string into another data type is available with almost all the nonstring data types you will work with, through the use of the Parse method. You can also convert data into Strings using the ToString method. This demonstration includes examples of methods inside the Convert class, to convert nonstring data types to and from each other.

 
VB Parse.aspx

[Run Sample] | [View Source]

First, you need to convert information from some arbitrary base data type into a string. The Object class (the class from which all other objects derive) has a ToString method that is automatically inherited by all other objects. Converting an object to a string may be less useful (if you don't override it, expect to receive the name of the class), so the derived class must override the method, and make it more useful. In its simplest form, the ToString method needs to be applied to an instance of a particular object, with no parameters, as in the following sample.


Dim intExample As Integer = 76
Dim strExample As String = intExample.ToString()

'  example one, having put the value in a string
Console.WriteLine("The string value is " & strExample)

'  example two, converting the integer to a string on the fly
Console.WriteLine("The string value is " & intExample.ToString())

'  example three, not converting the integer to a string at all???
Console.WriteLine("The string value is " & intExample)
VB

In the previous example, there are three lines being printed to the standard out stream. Which ones do you think will work? Believe it or not, all three lines will result in the same output to the output stream. The first one is hopefully pretty clear; having converted the integer to a string, you can concatenate that string to another string. The second one is fairly intuitive as well, if you remember that the ToString method on intExample returns a string, and therefore concatenates this return value onto the string being printed.

But what about the third example? This may look like it should not work, but in fact, there are some helpful routines that will convert nonstring data types into strings for you automatically (this is known as 'implicit conversion'). Don't rely on implicit conversion, however; until you learn where implicit conversion does and does not occur, you should use either of the first two examples.

To convert from a String to an integer, a Boolean, or some other non-String data type, use the non-instantiated Parse method, passing in the String you want to convert. The following lines are examples of using parse. To print the String you just parsed out to the screen, it needs to be converted back to a String by the WriteLine method.


Dim strExample1 As String = "true"
Dim strExample2 As String = "00.987"
Dim strExample3 As String = "127"
Dim strExample4 As String = "42"

Console.WriteLine( "Parsing {0} = {1}", strExample1, Boolean.Parse(strExample1) ) '  to boolean
Console.WriteLine( "Parsing {0} = {1}", strExample2, Double.Parse(strExample2) )  '  to double
Console.WriteLine( "Parsing {0} = {1}", strExample3, Int32.Parse( strExample3) )  '  to Int
Console.WriteLine( "Parsing {0} = {1}", strExample4, Byte.Parse(strExample4) )    '  to byte

Dim strExample5 As String = "three"

' catching any exceptions...
Try
     Console.WriteLine("The integer value is " & Int32.Parse(strExample5))
catch e As Exception
     Console.WriteLine("The value '{0}' cannot be converted to a integer value.", strExample5)
End Try
VB

Now that you can convert information to and from Strings, the next issue is how to convert information from other data types. Fortunately, there is a Convert class designed specifically for this. The Convert class has a number of static methods, beginning with 'To' and ending with the target data type of the Object you want to convert; for example, ToInt32 or ToByte. If successful, the returned variable from the method you use is an object of the target data type. Not all conversions will be possible when using the Convert method, so use a try...catch block if you think you may get uncertain results. The following examples demonstrate some of the 'To' methods in the Convert object.


Dim intExample as Integer = 76

'  the methods inside convert...
Console.WriteLine("Convert.ToString, result = {0}", Convert.ToString(intExample))   '  displays 76
Console.WriteLine("Convert.ToBoolean, result = {0}", Convert.ToBoolean(intExample)) '  displays True
Console.WriteLine("Convert.ToByte, result = {0}", Convert.ToByte(intExample))       '  displays 76
Console.WriteLine("Convert.ToChar, result =  {0}", Convert.ToChar(intExample))      '  displays L
Console.WriteLine("Convert.ToDouble, result = {0}", Convert.ToDouble(intExample))   '  displays 76
VB

If you want to convert dates into and out of strings (perhaps for formatting), you can use either the Parse method on the DateTime data type, or you can use a string's ToDateTime method. Both will achieve the same objective. Because dates can often be entered incorrectly by your users, don't forget to include appropriate exception handling to make sure that any conversion errors are caught. If you want to provide more control over parsing a date, see the ParseExact method.

Also note in the following sample that the first line forces this parse to work, because dates for the U.S. culture are used. If you want to try this code in your own culture, omit the first line, and then pick dates that make sense for your culture.


System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")

Dim strDate As String = "03/17/77"

'  Simple DateTime parsing
Console.WriteLine("Parsing {0}, using the Parse method.", strDate)

Dim d As DateTime = DateTime.Parse(strDate)
Console.WriteLine("The date parsed as {0}",d)

'  DateTime parsing using ParseExact
Dim strDate2 As String = "Thursday, March 17, 1977"
Console.WriteLine("Parsing {0}, using the ParseExact method.", strDate2)

Dim d2 As DateTime = DateTime.ParseExact(strDate2,"D", DBNull)
Console.WriteLine("The date parsed as {0}",d2)
VB

One great feature of parsing is that it allows you to remove unnecessary or mistyped information. For example, let's imagine that you have asked users to enter their area code as a set of three digits. People often just go ahead and type whatever they want, so users could put brackets and extra spaces on the front of the area code. Parsing can remove that information for you, rather than asking the user go back and retype the number, or perform some checking on the number yourself. In the following example, the enumeration NumberStyles is used to identify which style should be allowed from the user. The Bitwise '|' (BitOr in VB) is used as an 'or', indicating that the user may enter this string with parentheses, leading spaces, or trailing spaces, and the number is still acceptable. Note that a space in the middle of the number will not meet these requirements.


Dim toBeParsed As String = "   (555)   "

Console.WriteLine("Parsing the string {0}, with whitespace and parentheses", toBeParsed)

Dim j As Integer = Int32.Parse(toBeParsed, _
		NumberStyles.AllowParentheses BitOr NumberStyles.AllowLeadingWhite BitOr _
		NumberStyles.AllowTrailingWhite)

'  note that the output may well be negative, because of the parentheses
Console.WriteLine("The string parsed to {0}.", j)
VB

Summary

String and data type conversion and manipulation is essential when dealing with information on a daily basis. Because most screen inputs are automatically interpreted as textual or string information, it is often necessary to convert this information into other data types before you can use it appropriately. When dealing with conversions between base data types, keep the following items in mind:
  1. Use the ToString method to convert nonstring data types into strings.
  2. Avoid implicit conversions where possible.
  3. To convert string information into other data types, use the Parse method on the target datatype of your string conversion (for example, Boolean.Parse).
  4. To convert nonstring information from one data type to another, use any of the provided methods inside the Convert class, designed for this purpose. These methods begin with the word 'To' followed by the name of the target data type.
  5. Parsing can provide richer functionality when combined with the NumberStyles enumeration, to help parse incorrectly entered information into numerical data.


Copyright 2001 Microsoft Corporation. All rights reserved.