Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic "Scoping" of C# Checked Expression
    primarykey
    data
    text
    <p>Is it possible (in C#) to cause a <code>checked(...)</code> expression to have dynamic "scope" for the overflow checking? In other words, in the following example:</p> <pre><code>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 } </code></pre> <p>because in the expression <code>checked(add(max, 1))</code>, a <em>function call</em> causes the overflow, no <code>OverflowException</code> is thrown, even though there is an overflow during the <em>dynamic</em> extent of the <code>checked(...)</code> expression.</p> <p>Is there any way to cause both ways to evaluate <code>int.MaxValue + 1</code> to throw an <code>OverflowException</code>?</p> <p>EDIT: Well, either tell me if there is a way, or give me a better way to do this (please).</p> <p>The reason I think I need this is because I have code like:</p> <pre><code>void do_op(int a, int b, Action&lt;int, int&gt; forSmallInts, Action&lt;long, long&gt; forBigInts) { try { checked(forSmallInts(a, b)); } catch (OverflowException) { forBigInts((long)a, (long)b); } } ... do_op(n1, n2, (int a, int b) =&gt; Console.WriteLine("int: " + (a + b)), (long a, long b) =&gt; Console.WriteLine("long: " + (a + b))); </code></pre> <p>I want this to print <code>int: ...</code> if <code>a + b</code> is in the <code>int</code> range, and <code>long: ...</code> if the small-integer addition overflows. Is there a way to do this that is better than simply changing every single <code>Action</code> (of which I have many)?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload