[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Control overflow behavior with checked and unchecked in C#


C# handles overflow with different data types differently. You can control this to some extent with the checked and unchecked keywords.

If you execute code inside a checked block and an int or long operation causes an overflow, the block throws an exception.

If you execute code inside an unchecked block (or no block--this is the default behavior) and an int or long operation causes an overflow, the value simply overflows and creates a gibberish value without giving you any indication that there is a problem.

The following code uses longs to try to calculate the factorial function. If there is an overflow, the checked block throws an exception.

private string LongFactorial(long N) { // Long obeys checked and unchecked. try { checked { long result = 1; for (long i = 2; i <= N; i++) result *= i; return result.ToString(); } } catch (Exception ex) { return ex.ToString(); } }

Try changing this to an unchecked block or try removing the checked block to see what happens.

The float and double data types ignore checked and return Infinity if there's overflow.

The decimal type ignores unchecked and always throws an exception if there's overflow.

Nice and consistent, huh?

The following table summarizes how the data types behave.

Data Type Default Checked Unchecked
int Gibberish Exception Gibberish
long Gibberish Exception Gibberish
decimal Exception Exception Exception
float Infinity Infinity Infinity
double Infinity Infinity Infinity

The moral is to be aware of the kinds of failures a data type might produce. Unless you really don't care, use checked to catch exceptions with ints and longs, always catch exceptions with decimals, and look for Infinity with floats and doubles.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.