Encapsulates safely temporarily setting a variable value while some operation is performed.
VariableGuard safely encapsulates the following implementation pattern:
For example, to disable event handlers in a class, we might write:
EventHandler oldHandlers = SomeEvent;
SomeEvent = null;
DoOperation(arg1, arg2); // arg1 and arg2 are local variables
SomeEvent = oldHandlers.
Unfortunately, this isn't particularly safe since any exception thrown in DoOperation will leave SomeEvent disabled. We need a try/finally block to prevent this deleterious side-effect. This class encapsulates the pattern in a single call. Using an anonymous delegate, which is bound to its calling environment (a closure), the client code can invoke this guard using:
VariableGuard.Guard( SomeEvent, null, delegate { DoOperation(arg1, arg2); } );
Public Member Functions |
|
delegate void | GuardedCode () |
Delegate type for the delegate passed to the
Guard method below. |
|
Static Public Member Functions |
|
static void | Guard< T > (ref T variable, T value, GuardedCode guardedCode) |
Temporarily set variable to value while
calling the guardedCode delegate. |
delegate void CSharpUtilities::VariableGuard::GuardedCode | ( | ) |
Delegate type for the delegate passed to the Guard method below.
static void CSharpUtilities::VariableGuard::Guard< T > | ( | ref T | variable, |
T | value, | ||
GuardedCode | guardedCode | ||
) | [inline, static] |
Temporarily set variable to value while calling the guardedCode delegate.
See the class documentation for more information.
T | variable's type |
variable | reference parameter pointing to the variable to temporarily modify. |
value | the value to which to set the variable during the operation |
guardedCode | the operation delegate to call while variable is set to value. |