c# - Temporarily change a variable's value -


In an API implementation I am currently hacking, before doing some work, some variables need to be temporarily replaced, and they are done after the change which they were previously.

The current code looks like this:

  var _oldValue = _variable; _variable = tempValue; Try {doIt (); } Finally {_variable = oldValue; }   

By doing this, it is very annoying, unattractive, difficult to maintain, and leaves the actual algorithm under very disorganization, which only implements artifacts.

In C ++, I will create a square that stores an old value during construction, and restores it to its destroyer:

  {temp_value Tmp (variable_, temp_val); do it(); }   

While trying to do something like that in C # because apparently

So to remove that clutter, what must I do in C #?

PS: Feel free to fit any other tags. I failed to come up with any

Why not create a method that does for you, And then pass Lambda? Private Zero Seaglobels Ando A few (action dot) {var _oldValue = _ varariable; _variable = tempValue; Try {doit (); } Finally {_variable = _oldValue; }}

and to use it:

  SaveGlobal endosmaging ((=) => {DOSomething ();});   

Edit in response to the comment:

that doit sometimes assumes a problem is not there in the law DoSomething are not passing we have {DoSomething (); } For the method, you can easily write:

  int returnValue; Segloglobles and dosing (() => {returnValue = DoSomething ();});    

Comments