
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Safely Performing a Narrowing Numeric Cast
|
15
Solution
The simplest way to do this check is to use the checked keyword. The following
method accepts two
long data types and attempts to add them together. The result is
stuffed into an
int data type. If an overflow condition exists, the OverflowException
is thrown:
using System;
public void UseChecked(long lhs, long rhs)
{
int result = 0;
try
{
result = checked((int)(lhs + rhs));
}
catch (OverflowException e)
{
// Handle overflow exception here.
}
}
This is the simplest method. However, if you do not want the overhead of throwing an
exception and having to wrap a lot of code in
try/catch blocks to handle the overflow
condition, you can use the
MaxValue and MinValue fields of each type. A check using
these fields can be done prior to the conversion to insure that no loss of information
occurs. If this does occur, the code can inform the application that this cast will cause a
loss of information. You can use the following conditional statement to determine
whether
sourceValue can be cast to a short without losing any information:
// Our two variables are declared and initialized.
int sourceValue = 34000;
short destinationValue = 0;
// Determine if sourceValue will lose information in a cast to a short.
if (sourceValue <= short.MaxValue && sourceValue ...