How can I check if I'm in a checked context?

前端 未结 1 964
花落未央
花落未央 2021-01-19 04:17

How can I find out, using C# code, if I\'m in a checked context or not, without causing/catching an OverflowException, with the performance penalty

1条回答
  •  礼貌的吻别
    2021-01-19 04:36

    The only difference between a block that is checked vs unchecked are the IL instructions generated by the compiler for basic value type arithmetic operations. In other words, there is no observable difference between the following:

    checked {
      myType.CallSomeMethod();
    }
    

    and

    myType.CallSomeMethod();
    

    But lets say that there is an arithmetic operation, such as adding two integers. You would need to get the IL instructions for the method and check if the instructions around your method call are checked, and even that is far from bullet proof. You cannot tell if your custom operation is actually within the checked block, or just surrounded by checked blocks that it is not inside.

    Even catching an exception will not work, since you cannot differentiate between these two cases:

    checked {
      int a = (Some expression that overflows);
      myType.CallSomeMethod();
    }
    

    and

    checked {
      int a = (Some expression that overflows);
    }
    myType.CallSomeMethod();
    

    This is probably part of why the Decimal type does not attempt to detect checked vs unchecked and instead always throws OverflowException.

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