Permalink
Fetching contributors…
Cannot retrieve contributors at this time
63 lines (52 sloc) 2.65 KB
title ms.date ms.prod ms.technology ms.topic f1_keywords dev_langs helpviewer_keywords ms.assetid caps.latest.revision author ms.author translation.priority.ht
checked (C# Reference)
2015-07-20
.net
devlang-csharp
article
checked_CSharpKeyword
checked
CSharp
checked keyword [C#]
718a1194-988d-48a3-b089-d6ee8bd1608d
24
BillWagner
wiwagn
cs-cz
de-de
es-es
fr-fr
it-it
ja-jp
ko-kr
pl-pl
pt-br
ru-ru
tr-tr
zh-cn
zh-tw

checked (C# Reference)

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow. Evaluating the expression assigned to i2 in the following example does not cause a compiler error.

[!code-cscsrefKeywordsChecked#3]

By default, these non-constant expressions are not checked for overflow at run time either, and they do not raise overflow exceptions. The previous example displays -2,147,483,639 as the sum of two positive integers.

Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword. The following examples demonstrate how to use a checked expression or a checked block to detect the overflow that is produced by the previous sum at run time. Both examples raise an overflow exception.

[!code-cscsrefKeywordsChecked#4]

The unchecked keyword can be used to prevent overflow checking.

Example

This sample shows how to use checked to enable overflow checking at run time.

[!code-cscsrefKeywordsChecked#1]

C# Language Specification

[!INCLUDECSharplangspec]

See Also

C# Reference
C# Programming Guide
C# Keywords
Checked and Unchecked
unchecked