Checking various overflow conditions in .NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using static System.Console; | |
var m = int.MaxValue; | |
// possible solutions: | |
try | |
{ | |
WriteLine("n is an IntPtr"); | |
var n = IntPtr.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
var x = m + 5; | |
WriteLine(x); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
try | |
{ | |
WriteLine("n is a float"); | |
var n = float.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
var x = m + 5; | |
WriteLine(x); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
try | |
{ | |
WriteLine("n is a double"); | |
var n = double.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
var x = m + 5; | |
WriteLine(x); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
try | |
{ | |
WriteLine("n is a long, but filled with int.MaxValue (we're cheating a little bit here)"); | |
long n = int.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
var x = m + 5; | |
WriteLine(x); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
// these fail on the first addition: | |
try | |
{ | |
var n = nint.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
try | |
{ | |
var n = nuint.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
try | |
{ | |
var n = int.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
// decimal fails, even though it is a floating point number | |
try | |
{ | |
var n = decimal.MaxValue; | |
checked | |
{ | |
var y = n + 5; | |
WriteLine(y); | |
throw new Exception("Should not get here."); | |
} | |
} | |
catch (OverflowException) { } | |
// by default, C# does not check for overflow: | |
{ | |
var n = int.MaxValue; | |
var y = n + 5; | |
WriteLine(y); | |
} | |
// int.MaxValue + 1 is equal to int.MinValue | |
WriteLine("Is int.MaxValue + 1 == int.MinValue? " + (m + 1 == int.MinValue)); | |
WriteLine("Done!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment