What is the difference between checked and unchecked?

后端 未结 5 1017
情话喂你
情话喂你 2021-01-17 10:01

What is the difference between

checked(a + b)

and

unchecked(a + b)

?

相关标签:
5条回答
  • 2021-01-17 10:06

    The other answers cover the difference between the two. One thing worth noting is that if a and b are floats there will be no difference. It only works for integer operations.

    There is also a build option you can set so everything is checked. This will mean your app runs slightly slower but you won't need to put checked around your arithmetic operations.

    Here is a nice writeup that describes some pitfalls: http://www.codeproject.com/KB/cs/overflow_checking.aspx

    0 讨论(0)
  • 2021-01-17 10:15

    The Language Specification has a good article on the differences.

    The checked and unchecked operators are used to control the overflow checking context for integral-type arithmetic operations and conversions.

    class Test
    {
       static readonly int x = 1000000;
       static readonly int y = 1000000;
       static int F() {
          return checked(x * y);      // Throws OverflowException
       }
       static int G() {
          return unchecked(x * y);   // Returns -727379968
       }
       static int H() {
          return x * y;               // Depends on default
       }
    }
    
    0 讨论(0)
  • 2021-01-17 10:16

    It controls overflow checking for integer operations.

    0 讨论(0)
  • 2021-01-17 10:18

    if a + b is larger than the maximum value of the datatype, checked will throw an exception. Unchecked will roll the overflow of the value and add it to zero.

    0 讨论(0)
  • 2021-01-17 10:25

    Those are operators that check (or do not check) for overflow in the resulting numerical operation. In the checked case, an OverflowException exception is raised if the result of the operation exceeds the minimum or maximum value allowed for the datatype.

    More information is available from MSDN.

    0 讨论(0)
提交回复
热议问题