How to accomplish scoped variable reset in C#?
<p>One common pattern I see and use frequently in C++ is to temporarily set a variable to a new value, and then reset it when I exit that scope.  In C++, this is easily accomplished with references and templated scope classes, and allows for increased safety and prevention of errors where the variable is set to a new value, then reset to an incorrect assumed initial value.</p>

<p>Here is a simplified example of what I mean (in C++):</p>

<pre><code>void DoSomething()
{
    // The following line captures GBL.counter by reference, stores its current
    // value, and sets it to 1
    ScopedReset&lt;int&gt; resetter(GBL.counter, 1);

    // In this function and all below, GBL.counter will be 1
    CallSomethingThatNeedsCounterOf1();

    // When I hit the close brace, ~ScopedReset will be called, and it will
    // reset GBL.counter to it's previous value
}
</code></pre>

<p>Is there any way to do this in C#?  I've found the hard way that I can't capture a ref parameter inside an IEnumerator or a lambda, which were my first two thoughts.  I don't want to use the unsafe keyword if possible.</p>
