CSharpUtilities::VariableGuard Class Reference


Detailed Description

Encapsulates safely temporarily setting a variable value while some operation is performed.

VariableGuard safely encapsulates the following implementation pattern:

  • 1. Set a variable to a given value while performing an operation
  • 2. Perform the operation
  • 3. Set the variable back to its original value

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); } );

List of all members.

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.

Member Function Documentation

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,
value,
GuardedCode  guardedCode 
) [inline, static]

Temporarily set variable to value while calling the guardedCode delegate.

See the class documentation for more information.

Template Parameters:
T variable's type
Parameters:
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.

CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard
CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard CSharpUtilities::VariableGuard