. This string is obtained
. Finally, the contents of this string are read using
396
P a r t I :
T h e C # L a n g u a g e
Converting Numeric Strings to Their Internal Representation
Before leaving the topic of I/O, we will examine a technique useful when reading numeric
strings. As you know,
WriteLine( )
provides a convenient way to output various types of
data to the console, including numeric values of the built-in types, such as
int
and
double
.
Thus,
WriteLine( )
automatically converts numeric values into their human-readable form.
However, a parallel input method that reads and converts strings containing numeric
values into their internal, binary format is not provided. For example, there is no version of
Read( )
that reads from the keyboard a string such as “100” and then automatically converts
it into its corresponding binary value that can be stored in an
int
variable. Instead, there are
other ways to accomplish this task. Perhaps the easiest is to use a method that is defined for
all of the built-in numeric types:
Parse( )
.
Before we begin, it is necessary to state an important fact: All of C#’s built-in types, such
as
int
and
double
, are actually just
aliases
(that is, other names) for structures defined by the
.NET framework. In fact, the C# type and .NET structure type are indistinguishable. One is
just another name for the other. Because C#’s value types are supported by structures, the
value types have members defined for them.
For the numeric types, the .NET structure names and their C# keyword equivalents are
shown here:
.NET Structure Name
C# Name
Decimal
decimal
Double
double
Single
float
Int16
shor t
Int32
int
Int64
long
UInt16
ushor t
UInt32
uint
UInt64
ulong
Byte
byte
SByte
sbyte
These structures are defined inside the
System
namespace. Thus, the fully qualified
name for
Int32
is
System.Int32
. These structures offer a wide array of methods that help
fully integrate the value types into C#’s object hierarchy. As a side benefit, the numeric
structures also define a static method called
Parse( )
that converts a numeric string into
its corresponding binary equivalent.
There are several overloaded forms of
Parse( )
. The simplest version for each numeric
structure is shown here. It performs the conversion using the default locale and numeric
style. (Other versions let you perform locale-specific conversions and specify the numeric
style.) Notice that each method returns a binary value that corresponds to the string.
www.freepdf-books.com