Csharp/CSharp Tutorial/Data Type/checked
A Checked Block Example
<source lang="csharp">public class Program {
public static void Main() { checked { // int.MaxValue equals 2147483647 int n = int.MaxValue; n = n + 1 ; System.Console.WriteLine(n); } }
}</source>
Mark code block as checked
<source lang="csharp">using System; class MainClass {
public static void Main() { byte val1 = 200; byte val2 = 201; byte sum = (byte) (val1 + val2); // no exception checked { byte sum2 = (byte) (val1 + val2); // exception } }
}</source>
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at MainClass.Main()
Numeric Addition overflow for a byte
<source lang="csharp">using System; class MainClass {
public static void Main() { byte val1 = 200; byte val2 = 201; byte sum = (byte) (val1 + val2); // no exception checked { byte sum2 = (byte) (val1 + val2); // exception } }
}</source>