Skip to content

Instantly share code, notes, and snippets.

@michaelbartnett
Last active August 29, 2015 14:00
Show Gist options
  • Save michaelbartnett/11264523 to your computer and use it in GitHub Desktop.
Save michaelbartnett/11264523 to your computer and use it in GitHub Desktop.
A rough HashableWeakRef<T> implementation. Missing many details and cases.
using System;
class HashableWeakRef<T> : IEquatable<HashableWeakRef<T>> where T : class
{
private WeakReference weakRef;
public T Target { get { return (T) weakRef.Target; } }
public HashableWeakRef(T target)
{
weakRef = new WeakReference(target);
}
public override int GetHashCode()
{
var tmpTarget = weakRef.Target;
if (tmpTarget == null) {
throw new InvalidOperationException("Can't hash a null weak ref");
}
return tmpTarget.GetHashCode();
}
public override bool Equals(object other)
{
if (other is HashableWeakRef<T>) {
return this.Equals((HashableWeakRef<T>) other);
}
return false;
}
public bool Equals(HashableWeakRef<T> other)
{
var tmpOtherTarget = other.weakRef.Target;
var tmpThisTarget = this.weakRef.Target;
if (tmpOtherTarget == null || tmpThisTarget == null) {
throw new ArgumentNullException("Can't compare null weakrefs");
}
return tmpThisTarget.Equals(tmpOtherTarget);
}
public static bool operator ==(HashableWeakRef<T> a, HashableWeakRef<T> b)
{
var tmpTargetA = (T) a.weakRef.Target;
var tmpTargetB = (T) b.weakRef.Target;
if (tmpTargetA == null || tmpTargetB == null) {
throw new ArgumentNullException("Can't test equality for null weakrefs");
}
return tmpTargetA == tmpTargetB;
}
public static bool operator !=(HashableWeakRef<T> a, HashableWeakRef<T> b)
{
return !(a == b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment