When must we use checked operator in C#?

前端 未结 4 1821
野趣味
野趣味 2021-01-04 05:22

When must we use checked operator in C#?
Is it only suitable for exception handling?

4条回答
  •  醉酒成梦
    2021-01-04 05:29

    You would use checkedto guard against a (silent) overflow in an expression.
    And use unchecked when you know a harmless overflow might occur.

    You use both at places where you don't want to rely on the default (project-wide) compiler setting.

    Both forms are pretty rare, but when doing critical integer arithmetic it is worth thinking about possible overflow.

    Also note that they come in two forms:

     x = unchecked(x + 1);    // ( expression )
     unchecked { x = x + 1;}  // { statement(s) }
    

提交回复
热议问题