
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Converting Strings to Other Types
|
61
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
Discussion
The 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; ...