Skip to content

Instantly share code, notes, and snippets.

@stuartd
Created October 20, 2015 10:31
Show Gist options
  • Save stuartd/f94f9ab53e98f2795139 to your computer and use it in GitHub Desktop.
Save stuartd/f94f9ab53e98f2795139 to your computer and use it in GitHub Desktop.
// Adapted from http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
namespace Utilities
{
public struct HashCode
{
private readonly int hashCode;
private HashCode(int hashCode)
{
this.hashCode = hashCode;
}
public static HashCode Start
{
get { return new HashCode(17); }
}
public static implicit operator int(HashCode hashCode)
{
return hashCode.GetHashCode();
}
public HashCode Hash<T>(T obj)
{
var hash = !Equals(obj, default(T)) ? obj.GetHashCode() : 0;
return new HashCode(Hash(hash));
}
public HashCode Hash<T, K>(T obj, Func<T, K> expression)
{
int hash = 0;
if (Equals(obj, default(T)) == false)
{
K value = expression.Invoke(obj);
if (Equals(value, default(K)) == false)
{
hash = expression.Invoke(obj).GetHashCode();
}
}
return new HashCode(Hash(hash));
}
public override int GetHashCode()
{
return this.hashCode;
}
private int Hash(int newHashCode)
{
unchecked
{
return newHashCode + this.hashCode * 31; // 31 because it is a shift and subtract on the CPU
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment