Information Technology Reference
In-Depth Information
Parsing Strings to Data Values
Strings are arrays of Unicode characters. For example, string
"25.873"
is six characters long
and is
not
a number. Although it looks like a number, you cannot perform arithmetic functions
on it. “Adding” two strings produces a concatenation of them.
Parsing
allows you to take a string that represents a value and convert it into an actual
numeric value.
All the predefined, simple types have a static method called
Parse
, which takes a string
value representing the type and converts it into an actual value of the type.
The following statement shows an example of the syntax of using a
Parse
method. Notice
that
Parse
is static, so you need to invoke it by using the name of the target type.
double d1 = double.Parse("25.873");
↑
↑
Target type
String to be converted
The following code shows an example of parsing two strings to values of type
double
and
then adding them.
static void Main()
{
string s1 = "25.873";
string s2 = "36.240";
double d1 = double.Parse(s1);
double d2 = double.Parse(s2);
double total = d1 + d2;
Console.WriteLine("Total: {0}", total);
}
This code produces the following output:
Total: 62.113
If the string cannot be parsed, the system raises an exception. There is another static
method,
TryParse
, which returns
true
if the string was successfully parsed, and
false
other-
wise. It does not raise an exception if the parse fails.
■
Note
A common confusion about
Parse
is that, since it operates on a string, it is often thought of as a
member of the
string
class. It is not.
Parse
is not a single method at all, but a number of methods imple-
mented by the
target
types.