When must we use checked operator in C#?

前端 未结 4 1811
野趣味
野趣味 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) }
    
    0 讨论(0)
  • 2021-01-04 05:34

    From The checked and unchecked operators

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

    In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions.

    In an unchecked context, if an expression produces a value that is outside the range of the destination type, the result is truncated.

    checked, unchecked

    0 讨论(0)
  • 2021-01-04 05:37

    checked will help you to pick up System.OverFlowException which will go unnoticed otherwise

    int result = checked (1000000 * 10000000);   
        // Error: operation > overflows at compile time
    
    int result = unchecked (1000000 * 10000000);  
        // No problems, compiles fine
    
    0 讨论(0)
  • 2021-01-04 05:47

    checked vs. unchecked is also useful in those times when you are doing integer math. especially incrementing operations and you know you will increment past UInt32.MaxValue, and want it to harmlessly overflow back to 0.

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