
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Converting Between Simple Types in a Language-Agnostic Manner
|
133
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
initialValue = (float)13.5;
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
initialValue = (float)13.501;
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
This code outputs the following:
13
13
13
Notice that the resulting value was not rounded. Instead, the C# casting operator
simply truncates the fractional portion of the number.
Consistently casting numeric types in any language can be done through the static
methods on the
Convert class. The previous C# code can be converted to use the
ToInt32 method:
// C# Code:
finalValue = Convert.ToInt32((float)13.449);
Console.WriteLine(finalValue.ToString( ));
finalValue = Convert.ToInt32((float)13.5);
Console.WriteLine(finalValue.ToString( ));
finalValue = Convert.ToInt32((float)13.501);
Console.WriteLine(finalValue.ToString( ));
This code outputs the following:
13
14
14
Discussion
All conversions performed using methods on the Convert class are considered to be
in a checked context in C#. VB.NET does not have the concept of a checked or
unchecked context, so all conversions are considered to be in a checked context—an
unchecked context cannot be created in VB.NET.