2.15. Converting Strings to Their Equivalent Value Type

Problem

You 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, etc. 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).

Solution

Use 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);    // longString = "-7654.321

To convert a string containing a Boolean value to a Boolean 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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.