开发者

C# checked block

Can someone exp开发者_运维知识库lain to me what exactly is the checked an unchecked block ?

And when should I use each ?


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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜