Skip to content

Instantly share code, notes, and snippets.

@mpsenn
Forked from michaelbartnett/HashableWeakRefOfT.cs
Last active August 29, 2015 14:00
Show Gist options
  • Save mpsenn/11269927 to your computer and use it in GitHub Desktop.
Save mpsenn/11269927 to your computer and use it in GitHub Desktop.
using System;
class HashableWeakRef<T> : IEquatable<HashableWeakRef<T>> where T : class
{
private int hash;
private WeakReference weakRef;
public T Target { get { return (T) weakRef.Target; } }
public HashableWeakRef(T target)
{
weakRef = new WeakReference(target);
hash = target.GetHashCode();
}
public override int GetHashCode()
{
return hash;
}
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)
{
return (this == other);
}
public static bool operator ==(HashableWeakRef<T> a, HashableWeakRef<T> b)
{
if(a.hash != b.hash) {
return false;
}
var tmpTargetA = (T) a.weakRef.Target;
var tmpTargetB = (T) b.weakRef.Target;
if (tmpTargetA == null || tmpTargetB == null) {
return false;
}
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