Recipe 2.15. Converting Strings to Other TypesProblemYou have a string that represents the equivalent value of a number ("12"), char ("a"), bool ("true"), or a color enumeration ("Red"). You need to convert this string to its equivalent value type. Therefore, the number "12" would be converted to a numeric value such as int, short, float, and so on. The string "a" would be converted to a char value 'a', the string "true" would be converted to a bool value, and the color "Red" could be converted to an enumeration value (if an enumeration were defined that contained the element Red). SolutionUse the Parse static method of the type that the string is to be converted to. To convert a string containing a number to its numeric type, use the following code: // This code requires the use of the System and System.Globalization namespaces. string longString = "7654321"; int actualInt = Int32.Parse(longString); // longString = 7654321 string dblString = "-7654.321"; double actualDbl = Double.Parse(dblString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign); // dblString = "-7654.321" To convert a string containing a Boolean value to a bool type, use the following code: // This code requires the use of the System namespace. string boolString = "true"; bool actualBool = Boolean.Parse(boolString); // actualBool = true To convert a string containing a char value to a char type, use the following code: // This code requires the use of the System namespace. string charString = "t"; char actualChar = char.Parse(charString); // actualChar = 't' To convert a string containing an enumeration value to an enumeration type, use the following code: // This code requires the use of the System namespace. enum Colors { red, green, blue } string colorString = "blue"; // Note that the Parse method below is a method defined by System.Enum, // not by Colors. Colors actualEnum = (Colors)Colors.Parse(typeof(Colors), colorString); // actualEnum = blue DiscussionThe static Parse method available on certain data types allows easy conversion from a string value to the value of that specific value type. The Parse method is supported by the following types:
Notice that these types are all ValueTypes; other types, such as IPAddress, also support the Parse method. In addition to the Parse methods that take a single string parameter and convert it to the target data type, each numeric type has a second overloaded version of the Parse method that includes a second parameter of type System.Globalization.NumberStyles. This allows the Parse method to correctly handle specific properties of numbers, such as leading or trailing signs, decimal points, currency symbols, thousands separators, and so forth. NumberStyles is marked as a flag-style enumeration, so you can bitwise OR more than one enumerated value together to allow a group of styles to be used on the string. The NumberStyles enumeration is defined as follows:
If the NumberStyle parameter is not supplied when it is required (as when, for example, a numeric string includes a thousands separator) or if the NumberStyle enumeration is used on a string that does not contain a number in the supplied NumberStyle format, a FormatException exception will be thrown. If the size of the number in the string is too large or too small for the data type, an OverFlowException exception will be thrown. Passing in a null for the SourceString parameter will throw an ArgumentNullException exception. The Parse method of the two non-numeric data types, bool and char, also deserve some additional explanation. When calling Boolean.Parse, if a string value contains anything except a value equal to the static properties Boolean.FalseString, Boolean. TrueString, or the string literals "false" or "TRue" (which are case-insensitive), a FormatException exception is thrown. Passing in a null for the SourceString parameter throws an ArgumentNullException exception. When invoking char.Parse, if a string value containing more than one character is passed as its single argument, a FormatException exception is thrown. Passing in a null for the string parameter throws an ArgumentNullException exception. The static Enum.Parse method returns an Object of the same type as specified in the first parameter of this method (EnumType). This value is viewed as an Object type and must be cast to its correct enumeration type. This method throws an ArgumentException exception if the Value parameter cannot be matched to a string in the enumeration. An ArgumentNullException exception is thrown if a null is passed in to the Value parameter. If you do not want an exception to be thrown while attempting to convert a string to a particular type, consider using the tryParse method in types in which it is available. This method will not throw an exception if the conversion fails. Instead, it returns a Boolean true if the conversion succeeds and a false if the conversion fails. |