Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Unchecked Context

This C# example program demonstrates the unchecked keyword. Unchecked affects how overflow is handled.

Unchecked specifies overflow behavior.

Numeric types cause no exceptions when they overflow. This is the default behavior in C# programs. It is also specified with the unchecked keyword.

Tip: This feature specifies that overflow is an acceptable result of an operation such as increment—no exception is thrown.

Example. The unchecked keyword designates a section of code as not throwing exceptions when you assign, decrement or increment a variable past its bounds. The program uses the short type, which cannot exceed the value 32767.


In a checked context, an increment when the value is 32767 will throw an exception. But in an unchecked context, an increment will cause an overflow. The value will become invalid for most programs.

C# program that uses unchecked context

using System;

class Program
    static void Main()
	// The first short will overflow after the second short does.
	short a = 0;
	short b = 100;
	    // Keep incrementing the shorts until an exception is thrown.
	    // ... This is terrible program design.
	    while (true)
	    // Display the value of the shorts when overflow exception occurs.



This program shows both the checked and unchecked keywords. It is compiled by default in the unchecked context. We specify the unchecked context to make it clear that the second increment (b++) is not supposed to be checked.

Our program displays two numbers when the exception is thrown. The exception occurs because of the checked context. The a++ statement exceeds the bounds of the short type. The checked statement resulted in the highest valid short value.

And: The value of the b variable shows that overflow occurred and the short was incremented past its bounds and became negative.

Checked context. The checked context is more often useful than the unchecked context when you are specifying the keywords explicitly. This is because the unchecked context is the default when compiling C# programs in the Microsoft compiler.

And: You do not need to specify unchecked unless you have specified an enclosing checked context.


Tip: It is a good idea to use unchecked explicitly in cases where you are also using checked. This provides more symmetry.

Summary. The unchecked context changes program semantics from the checked context when incrementing values. This context is the default mode in which programs are compiled using Microsoft's C# compiler.