CHECKED AND UNCHECKED ARITHMETIC IN C# PROGRAMMING LANGUAGE

Overflows

When a continuance exceeds the limitations of a accumulation type, it is said to overflow. This crapper be an difficulty where unexpected, feat inaccurate results from calculations. It crapper modify be dangerous, specially when using vulnerable code, creating a pilot occupy danger that crapper be misused by vindictive software.

Unchecked Arithmetic

When using the choice C# programme options, arithmetic is unchecked. This effectuation that whatever high accumulation from arithmetic dealings is only truncated. In the mass distribution cipher this is demonstrated by environment an sort to its peak value, then incrementing it. The level continuance is short and kinda than existence a large sort is actually the smallest tolerable sort value.

int i = int.MaxValue;
Console.WriteLine(i);

i++;
Console.WriteLine(i);

/* OUTPUT 2147483647 -2147483648 */

Checked Arithmetic

To preclude the inaccurate or chanceful results of ungoverned calculations, checked arithmetic crapper be utilised instead. One artefact to attain this is to ingest the “checked” keyword for limited sections of code. This keyword uses a cipher country to touch a program of items that should be computerized in this way. If an stream occurs within a patterned cipher block, an omission of the identify System.OverflowException is thrown.

checked
{
    int i = int.MaxValue;
    Console.WriteLine(i);

    i++;
    Console.WriteLine(i);
}

Single statements haw also be patterned using the patterned keyword, with the countenance to be evaluated within parentheses. The mass cipher is functionally the aforementioned as the preceding example.

int i = int.MaxValue;
Console.WriteLine(i);

i = checked(i + 1);
Console.WriteLine(i);

Checked Compilation

If most or every of your cipher should be executed using patterned arithmetic, the assembling impact crapper be adjusted. For users of Visual Studio, the “Check for arithmetic overflow/underflow” choice crapper be designated from the modern physique options in a project’s properties.

If assembling from the bidding line, the “/checked+” alter crapper be utilised for patterned arithmetic and “/checked-” for ungoverned arithmetic by default.

Unchecked Code Blocks

In whatever circumstances you module desire to hit a send that is compiled using patterned arithmetic by choice but you haw ease poverty to take whatever sections of ungoverned code. This is achieved using the “unchecked” keyword. The structure is kindred to that of the “checked keyword”.

unchecked
{
    int i = int.MaxValue;
    Console.WriteLine(i);

    i++;
    Console.WriteLine(i);
}

Comments are closed.