Skip to content

Instantly share code, notes, and snippets.

@giggio
Created Nov 23, 2020
Embed
What would you like to do?
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