Is it possible (in C #) to force the checked(...) expression to have a dynamic "scope" to check for overflow? 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));
because in the checked(add(max, 1)) expression checked(add(max, 1)) function call causes an overflow, no OverflowException thrown, although the dynamic length of the checked(...) expression overflows.
Is there a way to get both ways to evaluate int.MaxValue + 1 to throw an OverflowException ?
EDIT: Well, tell me if there is a way, or give me a better way to do this (please).
I think I need this because I have code like:
void do_op(int a, int b, Action<int, int> forSmallInts, Action<long, long> forBigInts) { try { checked(forSmallInts(a, b)); } catch (OverflowException) { forBigInts((long)a, (long)b); } } ... do_op(n1, n2, (int a, int b) => Console.WriteLine("int: " + (a + b)), (long a, long b) => Console.WriteLine("long: " + (a + b)));
I want this to print int: ... if a + b is in the range of int and long: ... if the addition overflows with a small integer. Is there a way to do this better than just changing every Action (of which I have a lot)?