C# Keywords Tutorial Part 90: unchecked

C# Keywords Tutorial Part 90: unchecked

Strongly typed C# has several safety measures to aid in preventing runtime problems. It could be required to disable these safety safeguards and permit uncontrolled arithmetic operations in some circumstances, though. The term “unchecked” is useful in this situation.

The “unchecked” keyword is used to designate that no overflow checking should be done during an arithmetic operation. If the compiler encounters an overflow or underflow during an arithmetic operation when this keyword is present, no runtime exceptions will be raised. The outcome will be shortened or wrapped around instead.

Here’s an example of how the “unchecked” keyword can be used in C#:

int a = int.MaxValue;
int b = 1;

// This will throw an OverflowException
int c = a + b;

// This will not throw an exception and will wrap around to int.MinValue
unchecked
{
    int d = a + b;
}

In the above illustration, we’re attempting to multiply 1 by an integer’s maximum value (int.MaxValue). In a typical situation, this would cause an overflow and raise an OverflowException. The overflow is permitted and the result is wrapped around to the minimal value of an integer (int.MinValue) if the code is included in an unchecked block.

Another illustration of using the “unchecked” keyword with explicit casting is shown below:

byte a = 255;
byte b = 1;

// This will throw an OverflowException because 255 + 1 = 256, which is out of range for a byte
byte c = (byte)(a + b);

// This will not throw an exception and will result in 0, which is the wrapped around value of 256 for a byte
unchecked
{
    byte d = (byte)(a + b);
}

In this instance, we’re attempting to multiply 1 by 255 (a byte’s maximum value). Normally, when we try to cast the result to a byte, this would cause an overflow and raise an OverflowException. The overflow is permitted to occur and the outcome is wrapped around to 0, though, if the code is enclosed in an unchecked block.

It’s crucial to remember that if used incorrectly, the “unchecked” keyword might be harmful. It should only be utilized if you are certain that the outcome of a mathematical operation won’t result in any problems. Otherwise, you risk getting runtime problems that are hard to debug and unexpected behavior.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *