Skip to content

Instantly share code, notes, and snippets.

@jungrok5
Forked from derrickturk/Guard.cs
Created March 15, 2018 07:37
Show Gist options
  • Save jungrok5/b51c79062c4337794fa04319aac83b6d to your computer and use it in GitHub Desktop.
Save jungrok5/b51c79062c4337794fa04319aac83b6d 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