kbilsted / AutoHasher

Automatic generation of GetHashCode() methods using run-time code generation.
Apache License 2.0
6 stars 0 forks source link

AutoHasher

Join the chat at https://gitter.im/kbilsted/AutoHasher

Build status Nuget Nuget Nuget

Automatic generation of GetHashCode() methods using on the fly run-time code generation.

1. Advantages

Using this framework is a real treat. Here is what you get:

2. Usage

1. Define a class

using AutoHash;
using AutoHash.Attributes;
class Foo
{
  internal string field1 = "foo";
  internal int bar = 42;
  internal List<int> l1 = null;
  internal List<int> l2 = new List<int>() { 0, 0 };

  [DontHash]
  internal string nonHashed = "boo";
}

2. Implement GetHashCode() the same way for all classes

public override int GetHashCode()
{
  return AutoHasher.GetHashCode(this);
}

3. Check that it works

[TestFixture]
class UsageTest
{
  [Test]
  public void TestUsage()
  {
    var foo = new Foo();
    int expected = 0;
    expected = (expected * 397) ^ foo.field1.GetHashCode();
    expected = (expected * 397) ^ foo.bar.GetHashCode();
    expected = (expected * 397) ^ foo.l2.Count.GetHashCode();

    int actual = foo.GetHashCode();

    Assert.AreEqual(expected, actual);
  }
}

Notice that the field 'nonHashed' is not part of the hash code, and the collections are only participating with their length.