O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required