Interesting “params of ref” feature, any workarounds?

This is not possible. To explain why, first read my essay on why it is that we optimize deallocation of local variables of value type by putting them on the stack:

https://web.archive.org/web/20100224071314/http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx

Now that you understand that, it should be clear why you cannot store a “ref bool” in an array. If you could, then you could have an array which survives longer than the stack variable being referenced. We have two choices: either allow this, and produce programs which crash and die horribly if you get it wrong — this is the choice made by the designers of C. Or, disallow it, and have a system which is less flexible but more safe. We chose the latter.

But let’s think about this a little deeper. If what you want is to pass around “thing which allows me to set a variable”, we have that. That’s just a delegate:

static void DoStuff<T>(this T thing, params Action<T>[] actions)
{
    foreach(var action in actions) action(thing);
}
...
bool b = whatever;
b.DoStuff(x=>{q = x;}, x=>{r = x;} );

Make sense?

Leave a Comment