20.8. Safely Performing a Narrowing Numeric Cast

Problem

You need to cast a value from a larger value to a smaller one, while gracefully handling conditions that result in a loss of information. For example, casting a long to an int results in a loss of information only if the long data type is greater than int.MaxSize.

Solution

The simplest way to do this check is to use the checked keyword. The following extension 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 static class NumbersEnums
	{ 
	    public static void AddChecked(this long lhs, long rhs)
	    {
	        int result = checked((int)(lhs + rhs));
	    }
	}

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 ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.