26

I'm trying to get a hash (md5 or sha) of an object.

I've implemented this: http://alexmg.com/post/2009/04/16/Compute-any-hash-for-any-object-in-C.aspx

I'm using nHibernate to retrieve my POCOs from a database.
When running GetHash on this, it's different each time it's selected and hydrated from the database. I guess this is expected, as the underlying proxies will change.

Anyway,

Is there a way to get a hash of all the properties on an object, consistently each time?

I've toyed with the idea of using a StringBuilder over this.GetType().GetProperties..... and creating a hash on that, but that seems inefficient?

As a side note, this is for change-tracking these entities from one database (RDBMS) to a NoSQL store (comparing hash values to see if objects changed between rdbms and nosql)

2
  • Are the hashes stored between sessions? Sep 12, 2012 at 18:31
  • 1
    More information on how you are serializing deserializing these objects. And are you overwriting GetHashCode()?
    – paparazzo
    Sep 12, 2012 at 20:00

4 Answers 4

27

If you're not overriding GetHashCode you just inherit Object.GetHashCode. Object.GetHashCode basically just returns the memory address of the instance, if it's a reference object. Of course, each time an object is loaded it will likely be loaded into a different part of memory and thus result in a different hash code.

It's debatable whether that's the correct thing to do; but that's what was implemented "back in the day" so it can't change now.

If you want something consistent then you have to override GetHashCode and create a code based on the "value" of the object (i.e. the properties and/or fields). This can be as simple as a distributed merging of the hash codes of all the properties/fields. Or, it could be as complicated as you need it to be. If all you're looking for is something to differentiate two different objects, then using a unique key on the object might work for you.If you're looking for change tracking, using the unique key for the hash probably isn't going to work

I simply use all the hash codes of the fields to create a reasonably distributed hash code for the parent object. For example:

public override int GetHashCode()
{
    unchecked
    {
        int result = (Name != null ? Name.GetHashCode() : 0);
        result = (result*397) ^ (Street != null ? Street.GetHashCode() : 0);
        result = (result*397) ^ Age;
        return result;
    }
}

The use of the prime number 397 is to generate a unique number for a value to better distribute the hash code. See http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/ for more details on the use of primes in hash code calculations.

You could, of course, use reflection to get at all the properties to do this, but that would be slower. Alternatively you could use the CodeDOM to generate code dynamically to generate the hash based on reflecting on the properties and cache that code (i.e. generate it once and reload it next time). But, this of course, is very complex and might not be worth the effort.

An MD5 or SHA hash or CRC is generally based on a block of data. If you want that, then using the hash code of each property doesn't make sense. Possibly serializing the data to memory and calculating the hash that way would be more applicable, as Henk describes.

8
  • 1
    Object.GetHashCode does not return the memory address of the instance, since this can change during GC. It is actually just a random number generated on first access and pointed to by the object header. For more information, read up on the SyncBlockIndex, which is used for Hash Code and Monitor among other things. Jul 19, 2017 at 10:58
  • unchecked doesn't make sense here. Expressions that contain non-constant terms are unchecked by default at compile time and run time. See checked for information about enabling a checked environment. learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Apr 23, 2018 at 17:03
  • I've also found duplicates in relatively small sets of data using this method (about 100k items, each with about 30 properties that are involved in the hash) Apr 23, 2018 at 18:22
  • gethashcode should almost always be unchecked: csharpindepth.com/viewnote.aspx?noteid=186 Apr 24, 2018 at 16:10
  • Amount of duplicates really depends on the data. A single hash algorithm can't have perfect distribution for all data sets. Apr 24, 2018 at 16:12
12

If this 'hash' is solely used to determine whether entities have changed then the following algorithm may help (NB it is untested and assumes that the same runtime will be used when generating hashes (otherwise the reliance on GetHashCode for 'simple' types is incorrect)):

public static byte[] Hash<T>(T entity) 
{
  var seen = new HashSet<object>();
  var properties = GetAllSimpleProperties(entity, seen);
  return properties.Select(p => BitConverter.GetBytes(p.GetHashCode()).AsEnumerable()).Aggregate((ag, next) => ag.Concat(next)).ToArray();
}

private static IEnumerable<object> GetAllSimpleProperties<T>(T entity, HashSet<object> seen)
{
  foreach (var property in PropertiesOf<T>.All(entity))
  {
    if (property is int || property is long || property is string ...) yield return property;
    else if (seen.Add(property)) // Handle cyclic references
    {
      foreach (var simple in GetAllSimpleProperties(property, seen)) yield return simple;
    }
  }
}

private static class PropertiesOf<T>
{
  private static readonly List<Func<T, dynamic>> Properties = new List<Func<T, dynamic>>();

  static PropertiesOf()
  {
    foreach (var property in typeof(T).GetProperties())
    {
      var getMethod = property.GetGetMethod();
      var function = (Func<T, dynamic>)Delegate.CreateDelegate(typeof(Func<T, dynamic>), getMethod);
      Properties.Add(function);
    }
  }

  public static IEnumerable<dynamic> All(T entity) 
  {
    return Properties.Select(p => p(entity)).Where(v => v != null);
  }
} 

This would then be useable like so:

var entity1 = LoadEntityFromRdbms();
var entity2 = LoadEntityFromNoSql();
var hash1 = Hash(entity1);
var hash2 = Hash(entity2);
Assert.IsTrue(hash1.SequenceEqual(hash2));
0

Bumped into this question looking for something simple. I ended up doing this:

var serialized = JsonSerializer.Serialize(entity);
return Encoding.ASCII.GetBytes(serialized);
1
  • Consider using SHA256.ComputeHash() on that to generate a consistently sized hash, as a complex entity (containing lists of objects etc) could return a large byte[]. Oct 26, 2023 at 21:56
-1

GetHashCode() returns an Int32 (not an MD5).

If you create two objects with all the same property values they will not have the same Hash if you use the base or system GetHashCode().

String is an object and an exception.

string s1 = "john";
string s2 = "john";
if (s1 == s2) returns true and will return the same GetHashCode()

If you want to control equality comparison of two objects then you should override the GetHash and Equality.

If two object are the same then they must also have the same GetHash(). But two objects with the same GetHash() are not necessarily the same. A comparison will first test the GetHash() and if it gets a match there it will test the Equals. OK there are some comparisons that go straight to Equals but you should still override both and make sure two identical objects produce the same GetHash.

I use this for syncing a client with the server. You could use all the Properties or you could have any Property change change the VerID. The advantage here is a simpler quicker GetHashCode(). In my case I was resetting the VerID with any Property change already.

    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if (obj == null || !(obj is FTSdocWord)) return false;
        FTSdocWord item = (FTSdocWord)obj;
        return (OjbID == item.ObjID && VerID == item.VerID);
    }
    public override int GetHashCode()
    {
        return ObjID ^ VerID;
    }

I ended up using ObjID alone so I could do the following

if (myClientObj == myServerObj && myClientObj.VerID <> myServerObj.VerID)
{
   // need to synch
}

Object.GetHashCode Method

Two objects with the same property values. Are they equal? Do they produce the same GetHashCode()?

            personDefault pd1 = new personDefault("John");
            personDefault pd2 = new personDefault("John");
            System.Diagnostics.Debug.WriteLine(po1.GetHashCode().ToString());
            System.Diagnostics.Debug.WriteLine(po2.GetHashCode().ToString()); 
            // different GetHashCode
            if (pd1.Equals(pd2))  // returns false
            {
                System.Diagnostics.Debug.WriteLine("pd1 == pd2");
            }
            List<personDefault> personsDefault = new List<personDefault>();
            personsDefault.Add(pd1);
            if (personsDefault.Contains(pd2))  // returns false
            {
                System.Diagnostics.Debug.WriteLine("Contains(pd2)");
            }

            personOverRide po1 = new personOverRide("John");
            personOverRide po2 = new personOverRide("John");
            System.Diagnostics.Debug.WriteLine(po1.GetHashCode().ToString());
            System.Diagnostics.Debug.WriteLine(po2.GetHashCode().ToString());  
            // same hash
            if (po1.Equals(po2))  // returns true
            {
                System.Diagnostics.Debug.WriteLine("po1 == po2");
            }
            List<personOverRide> personsOverRide = new List<personOverRide>();
            personsOverRide.Add(po1);
            if (personsOverRide.Contains(po2))  // returns true
            {
                System.Diagnostics.Debug.WriteLine("Contains(p02)");
            }
        }



        public class personDefault
        {
            public string Name { get; private set; }
            public personDefault(string name) { Name = name; }
        }

        public class personOverRide: Object
        {
            public string Name { get; private set; }
            public personOverRide(string name) { Name = name; }

            public override bool Equals(Object obj)
            {
                //Check for null and compare run-time types.
                if (obj == null || !(obj is personOverRide)) return false;
                personOverRide item = (personOverRide)obj;
                return (Name == item.Name);
            }
            public override int GetHashCode()
            {
                return Name.GetHashCode();
            }
        }
4
  • 1
    @exacerbatedexpert But that is exactly the point. Any change is not necessarily a new version. Serialize / deserialzie could introduce a change in MD5 of an object that has not actually been changed. If I wear a different shirt tomorrow am I a different person? More unique is not the point. GetHashCode alone does not determine uniqueness. Equals determines uniqueness. The purpose of GetHashCode is a cheap way to reduce the number of calls to a more expensive Equals. It is the basis of HashSet and Dictionary
    – paparazzo
    Sep 14, 2012 at 1:27
  • @exacerbatedexpert But what about the case of deserialize uses system GetHash and the object with the same properties does not have the same MD5 because of a random GetHash?
    – paparazzo
    Sep 14, 2012 at 12:08
  • @exacerbatedexpert See the question "When running GetHash on this, it's different each time it's selected and hydrated from the database." OK serialization may not use GetHashCode directly but the Object does.
    – paparazzo
    Sep 14, 2012 at 15:01
  • @exacerbatedexpert OK implement. And I agree this is not about serialization. It is about the GetHashCode produced by an object.
    – paparazzo
    Sep 14, 2012 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.