Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 1

Now every arithmetic instruction subject to overflow within the code block (delimited by

the curly braces) is checked. In this particular example, theres only our addition operation,
so this code is equivalent to our previous snippet.

UNCHECKED AND HRESULT

You might wonder what the role of the unchecked keyword is and where it comes in
handy. For one thing, its possible to turn on overflow checking for a whole program, so
unchecked gives you an option to opt-out of overflow checking in some part of the code.
Another place where unchecked proves useful is when dealing with interop code that
needs to check for HRESULTs. Based on bit-level flags, HRESULTs have a high bit of 1,
which corresponds to the severity bit. A bit value of 1 indicates failure, making it very
popular in code that rigorously needs to check for failure conditions. As an example,
take a look at E_FAILs definition. If you have the Windows SDK installed, youll find
this in a file called WinError.h; otherwise, just take my word for it:
#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)
When dealing with such HRESULTs in C#, you typically want to declare symbolic

constants for them to make code more readable. You also want to make them signed
integers so that a Succeeded function can simply check for positive values and a
Failed function for negative ones:
const int E_FAIL = (int)0x80004005;

However, the compiler will complain that youre trying to assign a hexadecimal (positive)
literal within the uint range to a variable typed as int. Figure 5.15 illustrates the
compilers objection against such code.
To prevent this, the unchecked keyword comes in handy, used as an expression:
const int E_FAIL = unchecked((int)0x80004005);

Now the compiler will be fine with it, treating the hexadecimal as-is and just stuffing its
value in the E_FAIL variable.
But what if you want to protect your whole application against overflow conditions?
Requiring the use of the checked keyword everywhere is way too intrusive, so a compiler
flag exists to turn it on for the whole assembly. Not surprisingly, the flag is called
/checked, and it can also be enabled through the Visual Studio UI for the project settings.
Go to the project properties, open the Build tab, and click the Advanced button. An

You might also like