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
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
.