Numeric values are a part of most applications, whether it
is data entered by the user or values pulled from a backend data source. The
need to convert from one numeric type to another often arises during
development work. The .NET Framework provides numerous ways to perform the
conversion. In today’s column, we explore ways to perform numeric conversions
in both VB.NET and C#.
Choose your approach
As with most programming endeavors, there is more than one
way to convert numeric values. You could tackle the conversion with casting,
the convert function available in VB.NET, the Convert class, and so forth. We
begin with an examination of the Convert class.
Understand the Convert class
The Convert class allows you to convert a base data type to
another base data type. It returns a type whose value is equivalent to the
value of a specified type. A conversion method exists to convert every base
type to every other base type. However, the actual conversion operation
performed falls into three categories:
- A
conversion from a type to itself returns that type with no actual
conversion performed. - A
conversion which does not yield a valid result throws an InvalidCastException exception. No conversion is
actually performed. An exception is thrown for conversions from Char to
Boolean, Single, Double, Decimal or DateTime, and from those types to Char. An exception
is thrown for conversions from DateTime to any
type except String, and from any type, except String, to DateTime. - Any
base type, other than those described above, can be converted to and from
any other base type.
An exception will not be thrown if the conversion of a
numeric type results in a loss of precision (i.e., the loss of some least
significant digits). However, an exception will be thrown if the result is larger
than can be represented by the particular conversion method’s return value
type.
The Convert class contains the following methods for working
with numeric values:
- ToByte: Converts a specified value to an 8-bit
unsigned integer. - ToDecimal: Converts a specified value to a Decimal
number. - ToDouble: Converts a specified value to a
double-precision floating point number. - ToInt16:
Converts a specified value to a 16-bit signed integer. - ToInt32:
Converts a specified value to a 32-bit signed integer. - ToInt64:
Converts a specified value to a 64-bit signed integer. - ToSByte: Converts a specified value to an 8-bit signed
integer. - ToSingle: Converts a specified value to a
single-precision floating point number. - ToUInt16:
Converts a specified value to a 16-bit unsigned integer. - ToUInt32:
Converts a specified value to a 32-bit unsigned integer. - ToUInt64:
Converts a specified value to a 64-bit unsigned integer.
Each method is overloaded to handle the various values that
may be passed for conversion like Boolean, Unicode, decimal, floating point,
and so forth. The InvalidCastException exception
should be handled when dealing with conversions. The C# sample in Listing A provides a peek at how these
methods may be used. (Listing B contains
the VB.NET equivalent.)
The code is very simple, but it demonstrates how each method
may be used. It produces the following output from a console application:
0
100.5
100
100
100
100
100
100
3
100
100
Two conversions are performed for each Convert reference in
the previous example. First, the specified method of the Convert class is
called to perform the conversion. Next, the new value is converted to its
string representation for the Console.WriteLine call.
Now, some conversions will throw exceptions since the target
type is ill-suited for the value passed to it. Also, some casts are not
allowed. The code snippet in Listing C
demonstrates situations where exceptions may be generated.
The following output is generated:
Invalid Cast:Invalid cast from Char to Single.
Exception: Value was either too large or too small for an Int16.
Exception: Value was either too large or too small for an unsigned byte.
In addition, the .NET Framework will implicitly perform some
conversions. The most notable of such conversions is formatting a numeric value
for output by automatically calling its ToString
method. The example in Listing D
demonstrates both implicit and explicit conversion when finding the sum of a
group of values. (Listing E contains
the equivalent VB.NET code.)
The byte and short values are implicitly converted to
integer while the decimal, long, and decimal values must be explicitly
converted for the code to compile. If you do attempt to compile the code
without explicitly converting one of the values (such as the decimal value), it
will yield the following compile error:
Cannot implicitly convert type 'double' to 'int'.
Alternatives to the Convert class
While the Convert class provides everything necessary to
convert from one numeric type to another, it is not the only way to accomplish
a conversion. For example, in C#, you may directly cast one value to another.
Also, the DirectCast and specific functions like CInt are available for use in VB.NET as well as CType. Regular expressions provide another way to convert
some numeric values. This is only a sampling, but you need to be aware of the
alternatives.
Get what you need
Numeric operations require a consistent set of values. While
the .NET Framework will implicitly perform some conversions like a numeric
value to string or byte to integer, others require explicit conversion. The
Convert class provides the methods necessary to convert from one numeric base
to another.
TechRepublic’s free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!