Created
July 8, 2016 15:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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