Skip to content

Instantly share code, notes, and snippets.

@rossmurray
Created November 21, 2014 16:21
Show Gist options
  • Save rossmurray/4616686468bd8958beeb to your computer and use it in GitHub Desktop.
Save rossmurray/4616686468bd8958beeb to your computer and use it in GitHub Desktop.
Return an IDisposable instance of T and control what happens on Dispose, without making a whole class for it.
public static class DisposableWrapper
{
public static DisposableWrapper<T> Wrap<T>(T wrapped, Action onDispose)
{
return new DisposableWrapper<T>(wrapped, onDispose);
}
}
public class DisposableWrapper<T> : IDisposable
{
public T Item { get; private set; }
private Action onDispose;
public DisposableWrapper(T wrapped, Action onDispose)
{
this.Item = wrapped;
this.onDispose = onDispose;
}
public DisposableWrapper<U> Into<U>(DisposableWrapper<U> other)
{
return new DisposableWrapper<U>(other.Item, () =>
{
other.Dispose();
this.Dispose();
});
}
public DisposableWrapper<T> With<U>(DisposableWrapper<U> other)
{
return new DisposableWrapper<T>(this.Item, () =>
{
other.Dispose();
this.Dispose();
});
}
public void Dispose()
{
var a = this.onDispose;
if(a != null)
{
a();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment