Skip to content

Instantly share code, notes, and snippets.

@DForshner
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save DForshner/90175edc7806af3a376d to your computer and use it in GitHub Desktop.

Select an option

Save DForshner/90175edc7806af3a376d to your computer and use it in GitHub Desktop.
By implementing the IDisposiable interface we can use the using keyword which will call the Dispose method restoring the original value. This is not thread safe as the temporary state change will be visible to other threads.
public class CustomScope : IDisposable
{
private readonly State originalState;
public CustomScope(State state)
{
this.originalState = GlobalSingleton.State;
GlobalSingleton.State = state;
}
public void Dispose()
{
GlobalSingleton.State = originalState;
}
}
// Example:
using (CustomScope scope = new CustomScope(newState))
{
// New state.
}
// Original state has been restored.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment