Created
November 21, 2014 16:21
-
-
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.
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
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