Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created July 8, 2016 15:29
Show Gist options
  • Save derrickturk/a3e59cb08ee41728d624fcb9d1bf6d97 to your computer and use it in GitHub Desktop.
Save derrickturk/a3e59cb08ee41728d624fcb9d1bf6d97 to your computer and use it in GitHub Desktop.
A (kind of cruddy) scope guard for C#. The T: class constraint can be dropped at the expense of the null check.
class Guard<T> : IDisposable where T : class {
public Guard(T obj, Action<T> dispose)
{
obj_ = obj;
dispose_ = dispose;
disposed_ = false;
}
public void Dispose()
{
// the "official" pattern is dumb boilerplate
// for this application
if (!disposed_ && obj_ != null)
dispose_(obj_);
disposed_ = true;
}
public T Get()
{
return obj_;
}
private T obj_;
private Action<T> dispose_;
private bool disposed_;
}
static class Guard {
public static Guard<T> MakeGuard<T>(T obj, Action<T> dispose)
where T : class
{
return new Guard<T>(obj, dispose);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment