Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CallWithEscapeContinuation
using System;
class Program
{
sealed class EscapeContinuation<T> : Exception
{
public T Value { get; private set; }
public void Raise(T value)
{
Value = value;
throw this;
}
}
static R CallWithEscapeContinuation<R>(Func<Action<R>, R> call)
{
var ec = new EscapeContinuation<R>();
try
{
return call(ec.Raise);
}
catch (EscapeContinuation<R> c)
{
if (c == ec)
{
return c.Value;
}
else
{
throw;
}
}
}
static void Main(string[] args)
{
var index = CallWithEscapeContinuation<int>(ec =>
{
ec(40);
return -1;
});
Console.WriteLine(index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment