Temporarily change a variable's value
<p>In an API implementation I'm currently hacking on, there's the need to repeatedly change some variables temporarily, before doing some task, and change them back after the task is done to whatever they were before. </p>

<p>The current code looks like this: </p>

<pre><code>var _oldValue = _variable;
_variable = tempValue;
try
{
  doIt();
}
finally
{
  _variable = oldValue;
}
</code></pre>

<p>Doing this a lot is annoying, ugly, hard to maintain, and buries the actual algorithms under a lot of clutter that's just implementation artifacts. </p>

<p>In C++, I would make a class which stores the old value somewhere during construction, and restores it in its destructor: </p>

<pre><code>{
  temp_value tmp(variable_, temp_val);
  do_it();
}
</code></pre>

<p>When trying to do something similar in C# <a href="http://stackoverflow.com/questions/5463666/can-i-store-a-reference-to-an-variable-in-an-object/">I failed</a> because apparently <a href="http://stackoverflow.com/questions/2760087/storing-a-reference-to-an-object-in-c/2760111#2760111">C# can't store references to other objects in classes</a>. </p>

<p>So what would I have to do in C# to remove that clutter? </p>

<p>P.S.: Feel free to add any other tags you see fit. I failed to come up with any. </p>
