C# checked block
Asked Answered
C

3

25

Can someone explain to me what exactly is the checked an unchecked block ?
And when should I use each ?

Cupping answered 7/3, 2011 at 9:23 Comment(0)
S
41

Arithmetic overflow; for example:

int i = int.MaxValue -10;
checked {       
   i+= 20; // boom: OverflowException
           // "Arithmetic operation resulted in an overflow."
}

So use checked when you don't want accidental overflow / wrap-around to be a problem, and would rather see an exception.

unchecked explicitly sets the mode to allow overflow; the default is unchecked unless you tell the compiler otherwise - either through code (above) or a compiler switch (/checked in csc).

Skeg answered 7/3, 2011 at 9:27 Comment(3)
This is old but couldn't we just use a try/catch instead? Just trying to figure out use case scenario.Geoff
@Geoff nope; the entire point here is to cause an error; by default c# uses unchecked arithmetic, so overflows happen silently. Adding a try/catch won't do anything if it never throws. It is adding the checked that makes it throw on overflowSkeg
Thanks for clarifying.Geoff
S
13

From MSDN

C# statements can execute in either checked or unchecked context. In a checked context, arithmetic overflow raises an exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated.

In short, they are used to define the context in which the arithmetic operations take place. In the checked context an exception is thrown when overflow happens. In an unchecked context an exception is not thrown and the value is wrapped-around instead.

Now, whether your context is unchecked or checked depends on your compiler options. So if you want to manually override the context, i.e perform a checked operation in an otherwise unchecked context or vice-versa, you should use these keywords.

For more details and examples follow the link given above.

Sulfanilamide answered 7/3, 2011 at 9:26 Comment(1)
unchecked blocks are good from when you want overflow to just wrap around, like when calculating a hashcode.Weinstock
L
7

checked blocks use to handle arithmetic overflow/underflow situations. For a example:

Let's say you want to convert an int value into a short type value (called a narrowing conversion). int type variable can have value range from -2,147,483,648 to 2,147,483,647. But short can have only from -32,768 to 32,767.

Due to that reason short variable can not have all possible values that an int variable can have. If some how, one may cast as following example:

                int y = 1000000000;
                short x = (short)y;

Clearly you can see value of y is in outside the valid values for a short variable. So arithmetic overflow situation take place.

By default C# doesn't throw any exception for above code. But there are few ways you can throw an exception and handle it. In that case checked blocks comes in handy

        try
        {
            checked
            {
                int y = 1000000000;
                short x = (short)y;
            }
        }
        catch (OverflowException ex)
        {
            MessageBox.Show("hey, we got a overflow/underflow situation");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error");
        }

catch block caused throwing an overflow exception,if casting caused an overflow/underflow situation. In this case it shows the error message

"hey, we got a overflow/underflow situation"

unchecked blocks are use if we want to discard the underflow/overflow when a conversion happened and continue the operation.

Lissa answered 2/4, 2015 at 5:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.