Checked and unchecked arithmetic helps you control how your program handles math operations that go beyond the limits of numbers.
0
0
Checked and unchecked arithmetic in C Sharp (C#)
Introduction
When you want to catch errors if numbers get too big or too small during math.
When you want your program to ignore overflow and continue without errors.
When working with financial or critical calculations where mistakes must be caught.
When debugging to find where overflow happens in your code.
When you want to improve performance by skipping overflow checks.
Syntax
C Sharp (C#)
checked {
// code where overflow causes an exception
}
unchecked {
// code where overflow is ignored
}checked makes the program throw an error if numbers overflow.
unchecked lets the program continue even if numbers overflow.
Examples
This will cause an error because the sum is too big for an int.
C Sharp (C#)
int a = int.MaxValue; int b = 1; int c = checked(a + b);
This will not cause an error. The result wraps around to a negative number.
C Sharp (C#)
int a = int.MaxValue; int b = 1; int c = unchecked(a + b);
Using a checked block to catch overflow in multiple lines.
C Sharp (C#)
checked {
int x = int.MaxValue;
int y = 1;
int z = x + y; // Overflow exception here
}Using an unchecked block to ignore overflow in multiple lines.
C Sharp (C#)
unchecked {
int x = int.MaxValue;
int y = 1;
int z = x + y; // No error, wraps around
}Sample Program
This program shows how checked throws an error when numbers overflow, while unchecked lets the number wrap around.
C Sharp (C#)
using System; class Program { static void Main() { int max = int.MaxValue; try { int resultChecked = checked(max + 1); Console.WriteLine($"Checked result: {resultChecked}"); } catch (OverflowException) { Console.WriteLine("Overflow caught in checked operation!"); } int resultUnchecked = unchecked(max + 1); Console.WriteLine($"Unchecked result: {resultUnchecked}"); } }
OutputSuccess
Important Notes
By default, arithmetic operations are unchecked unless you enable checked context.
You can enable checked arithmetic for the whole project in project settings if needed.
Use checked blocks when you want to be sure no overflow happens silently.
Summary
Use checked to catch overflow errors in math operations.
Use unchecked to ignore overflow and allow wrapping.
Checked and unchecked help you control how your program handles big or small numbers.