Skip to content

Instantly share code, notes, and snippets.

@steverichey
Created May 14, 2020 14:02
Show Gist options
  • Save steverichey/ca84c60df11d3722602d20ddcacc793a to your computer and use it in GitHub Desktop.
Save steverichey/ca84c60df11d3722602d20ddcacc793a to your computer and use it in GitHub Desktop.
A C# class to call a method when the object goes out of scope.
/// <summary>
/// Performs an action when disposed.
/// <code>
/// using (new PerformOnExit(Foo))
/// {
/// Bar();
/// }
/// </code>
/// </summary>
public sealed class PerformOnExit : IDisposable
{
readonly Action action;
/// <summary>
/// Initializes a new instance of the <see cref="PerformOnExit"/> class.
/// </summary>
/// <param name="action">An action to invoke when this object gets disposed.</param>
public PerformOnExit(Action action)
{
this.action = action;
}
/// <inheritdoc/>
public void Dispose()
{
action();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment