Wednesday, 14 August 2013

Dynamic "Scoping" of C# Checked Expression

Dynamic "Scoping" of C# Checked Expression

Is it possible (in C#) to cause a checked(...) expression to have dynamic
"scope" for the overflow checking? In other words, in the following
example:
int add(int a, int b)
{
return a + b;
}
void test()
{
int max = int.MaxValue;
int with_call = checked(add(max, 1)); // does NOT cause OverflowException
int without_call = checked(max + 1); // DOES cause OverflowException
}
because in the expression checked(add(max, 1)), a function call causes the
overflow, no OverflowException is thrown, even though there is an overflow
during the dynamic extent of the checked(...) expression.
Is there any way to cause both ways to evaluate int.MaxValue + 1 to throw
an OverflowException?
EDIT: Well, either tell me if there is a way, or give me a better way to
do this (please).

No comments:

Post a Comment