What is the difference between checked and unchecked?

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

What is the difference between

checked(a + b)

and

unchecked(a + b)

?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    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
       }
    }
    

提交回复
热议问题