Skip to content

Instantly share code, notes, and snippets.

@giggio
Created November 23, 2020 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giggio/337d10cb80f128c225d1526e5b0fdf3d to your computer and use it in GitHub Desktop.
Save giggio/337d10cb80f128c225d1526e5b0fdf3d to your computer and use it in GitHub Desktop.
Checking various overflow conditions in .NET
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