How can I check if I am in a verified context?

How can I find out, using C # code, if I am in the checked context or not, without causing / not catching OverflowException , while not observing performance?

+5
source share
1 answer

The only difference between a block that is checked vs unchecked is the IL instructions created by the compiler for arithmetic operations with a base type value. In other words, there is no noticeable difference between the following:

 checked { myType.CallSomeMethod(); } 

and

 myType.CallSomeMethod(); 

But let's say that there is an arithmetic operation, for example, adding two integers. You will need to get the IL instructions for this method and check if the instructions around your method call are checked, and even this is far from bullet proof. You cannot determine if your user operation is really within the checked block or just surrounded by marked blocks in which it is not inside.

Even catching an exception will not work, since you cannot distinguish 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 Decimal not try to detect checked vs unchecked and instead always throws an OverflowException .

+4
source

Source: https://habr.com/ru/post/1211674/


All Articles