Skip to content

Instantly share code, notes, and snippets.

@Porges
Created January 29, 2015 21:48
Show Gist options
  • Save Porges/a5a2bacdcc3650a8620e to your computer and use it in GitHub Desktop.
Save Porges/a5a2bacdcc3650a8620e to your computer and use it in GitHub Desktop.
disposables where ownership can be transferred
public struct Owned<T> : IDisposable
where T : class, IDisposable
{
private T _value;
public Owned(T value)
{
_value = value;
}
public T Value => _value;
public T Exchange(T newValue) => Interlocked.Exchange(ref _value, newValue);
public T Release() => Exchange(null);
public Owned<T> Move() => Owned.Create(Release());
public void Dispose() => Release()?.Dispose();
}
public static class Owned
{
public static Owned<T> Create<T>(T value)
where T : class, IDisposable
{
return new Owned<T>(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment