Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata