An Unchecked Block Example
using System;
public class Program
{
public static void Main()
{
unchecked
{
// int.MaxValue equals 2147483647
int n = int.MaxValue;
n = n + 1 ;
System.Console.WriteLine(n);
}
}
}
Mark expressions as unchecked
using System;
class MainClass
{
public static void Main()
{
unchecked
{
byte a = 55;
byte b = 210;
byte c = (byte) (a + b);
}
}
}
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
at MainClass.Main()
Overflow the max value of a System.Byte
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
byte b1 = 100;
byte b2 = 250;
try
{
byte sum = unchecked((byte)(b1 + b2));
Console.WriteLine("sum = {0}", sum);
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
}
}
unchecked marker
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
// Declare two shorts to add.
short numb1 = 30000, numb2 = 30000;
// This will not throw an exception.
unchecked
{
short answer = (short)Add(numb1, numb2);
Console.WriteLine("{0} + {1} = {2}",
numb1, numb2, answer);
}
}
static int Add(int x, int y){ return x + y; }
}