PkmnLibSharp/PkmnLibSharp/Utilities/ScopedOwner.cs

75 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
namespace PkmnLibSharp.Utilities
{
/// <summary>
/// Helper class to ensure an object is disposed when it goes out of scope.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ScopedOwner<T> : IDisposable where T : PointerWrapper
{
public T? Value { get; private set; }
public ScopedOwner(T value)
{
Value = value;
}
public T? TakeOwnership()
{
var val = Value;
Value = null;
return val;
}
~ScopedOwner()
{
if (Value != null)
Value.Dispose();
}
public static implicit operator T?(ScopedOwner<T> val) => val.Value;
public override string ToString()
{
if (Value == null) return "null";
return Value.ToString();
}
public void Dispose()
{
if (Value != null)
Value.Dispose();
Value = null;
}
protected bool Equals(ScopedOwner<T> other)
{
return EqualityComparer<T?>.Default.Equals(Value, other.Value);
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((ScopedOwner<T>) obj);
}
public override int GetHashCode()
{
return EqualityComparer<T?>.Default.GetHashCode(Value);
}
public static bool operator ==(ScopedOwner<T>? left, ScopedOwner<T>? right)
{
return Equals(left, right);
}
public static bool operator !=(ScopedOwner<T>? left, ScopedOwner<T>? right)
{
return !Equals(left, right);
}
}
}