13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATIONFor non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by anychecked or unchecked operators or statements, the default overflow checking context is unchecked,unless external factors (such as compiler switches and execution environment configuration) call forchecked evaluation.For constant expressions (expressions that can be fully evaluated at compile-time), the default overflowchecking context is always checked. Unless a constant expression is explicitly placed in an uncheckedcontext, overflows that occur during the compile-time evaluation of the expression always cause compiletimeerrors.[Note: Developers may benefit if they exercise their code using checked mode (as well as unchecked mode).It also seems reasonable that, unless otherwise requested, the default overflow checking context is set tochecked when debugging is enabled. end note][Example: In the exampleclass Test{static readonly int x = 1000000;static readonly int y = 1000000;static int F() {return checked(x * y); // Throws OverflowException}static int G() {return unchecked(x * y); // Returns -727379968}static int H() {return x * y;// Depends on default}}no compile-time errors are reported since neither of the expressions can be evaluated at compile-time. Atrun-time, the F method throws a System.OverflowException, and the G method returns –727379968(the lower 32 bits of the out-of-range result). The behavior of the H method depends on the default overflowchecking context for the compilation, but it is either the same as F or the same as G. end example][Example: In the exampleclass Test{const int x = 1000000;const int y = 1000000;static int F() {return checked(x * y); // Compile error, overflow}static int G() {return unchecked(x * y); // Returns -727379968}static int H() {return x * y;// Compile error, overflow}}the overflows that occur when evaluating the constant expressions in F and H cause compile-time errors tobe reported because the expressions are evaluated in a checked context. An overflow also occurs whenevaluating the constant expression in G, but since the evaluation takes place in an unchecked context, theoverflow is not reported. end example]The checked and unchecked operators only affect the overflow checking context for those operations thatare textually contained within the “(” and “)” tokens. The operators have no effect on function membersthat are invoked as a result of evaluating the contained expression. [Example: In the example152

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!