Question

I've asked this question recently a few different ways, but don't get an answer that tells me how a Dictionary of <T,U> needs to be handled when I hold a reference to something that changes T.GetHashCode(). For the purpose of this question "state" refers to the properties and fields that is also checked when Equals() is checked. Assume all public, internal and protected members are included.

Given that I have a C# object that

  • Overrides GetHashCode, and Equals

  • This object is saved to a Dictionary as a Key value (note my understanding is that Dictionary will read the GetHashCode value at this point in time)

  • I search for the object by Key and modify a value. (Modifying this value modifies my custom equals function and possibly gethashcode)

My question is, what should GetHashCode reflect? Should the return of this function reflect the original state of the object or the modified state?

Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrustMap
{
    class Program
    {
       static  Dictionary<Model.TrustedEntityReference, string> testDictionary = new Dictionary<Model.TrustedEntityReference, string>();

        static void Main(string[] args)
        {
            Model.TrustedEntity te = new Model.TrustedEntity();

            te.BackTrustLink = null;
            te.ForwardTrustLink = null;
            te.EntryName = "test1";

            var keyValue =  new Model.TrustedEntityReference()
            {
                HierarchyDepth = 1,
               trustedEntity = te 
            };

            testDictionary.Add(keyValue, "some data");

            // Now that I have a reference to the Key outside the object
            te.EntryName = "modified data";

            // Question: how should TE respond to the change, considering that it's a part of a dictionary now?
            //           If this is a implementation error, how should I track of objects that are stored as Keys that shouldn't be modified like I did in the previous line?

        }
    }

}

namespace Model
{
    public class TrustedEntity
    {
        public TrustedEntity()
        {
            this.BackTrustLink = new List<TrustedEntityReference>();
            this.ForwardTrustLink = new List<TrustedEntityReference>();
        }

        public List<TrustedEntityReference> BackTrustLink { get; set; }

        public string EntryName { get; set; }

        public List<TrustedEntityReference> ForwardTrustLink { get; set; }

    }

    public class TrustedEntityReference 
    {
        public int HierarchyDepth { get; set; }
        public TrustedEntity trustedEntity {get; set; }

        public override bool Equals(object obj)
        {
            if (obj.GetType() != trustedEntity.GetType())
                return false;

            TrustedEntity typedObj = (TrustedEntity)obj;

            if (typedObj.BackTrustLink != null)
            { 
                if (trustedEntity.BackTrustLink != typedObj.BackTrustLink)
                    return false;
            }

            if (typedObj.ForwardTrustLink != null)
            {
                if (trustedEntity.ForwardTrustLink != typedObj.ForwardTrustLink)
                    return false;
            }

            if (trustedEntity.EntryName != typedObj.EntryName)
                return false;

            return true;
        }

        /// <summary>
        /// If the hash-code for two items does not match, they may never be considered equal
        /// Therefore equals may never get called.
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {

            // if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
            // if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.
           // return base.GetHashCode();
            return StackOverflow.System.HashHelper.GetHashCode<int, TrustedEntity>(this.HierarchyDepth, this.trustedEntity);
        }
    }


}

namespace StackOverflow.System
{
    /// <summary>
    /// Source https://stackoverflow.com/a/2575444/328397
    /// 
    /// Also it has extension method to provide a fluent interface, so you can use it like this:
///public override int GetHashCode()
///{
///    return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);
///}
///or like this:

///public override int GetHashCode()
///{
///    return 0.CombineHashCode(Manufacturer)
///        .CombineHashCode(PartN)
///        .CombineHashCode(Quantity);
///}
    /// </summary>
    public static class HashHelper
    {
        public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
        {
            unchecked
            {
                return 31 * arg1.GetHashCode() + arg2.GetHashCode();
            }
        }

        public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
        {
            unchecked
            {
                int hash = arg1.GetHashCode();
                hash = 31 * hash + arg2.GetHashCode();
                return 31 * hash + arg3.GetHashCode();
            }
        }

        public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3,
            T4 arg4)
        {
            unchecked
            {
                int hash = arg1.GetHashCode();
                hash = 31 * hash + arg2.GetHashCode();
                hash = 31 * hash + arg3.GetHashCode();
                return 31 * hash + arg4.GetHashCode();
            }
        }

        public static int GetHashCode<T>(T[] list)
        {
            unchecked
            {
                int hash = 0;
                foreach (var item in list)
                {
                    hash = 31 * hash + item.GetHashCode();
                }
                return hash;
            }
        }

        public static int GetHashCode<T>(IEnumerable<T> list)
        {
            unchecked
            {
                int hash = 0;
                foreach (var item in list)
                {
                    hash = 31 * hash + item.GetHashCode();
                }
                return hash;
            }
        }

        /// <summary>
        /// Gets a hashcode for a collection for that the order of items 
        /// does not matter.
        /// So {1, 2, 3} and {3, 2, 1} will get same hash code.
        /// </summary>
        public static int GetHashCodeForOrderNoMatterCollection<T>(
            IEnumerable<T> list)
        {
            unchecked
            {
                int hash = 0;
                int count = 0;
                foreach (var item in list)
                {
                    hash += item.GetHashCode();
                    count++;
                }
                return 31 * hash + count.GetHashCode();
            }
        }

        /// <summary>
        /// Alternative way to get a hashcode is to use a fluent 
        /// interface like this:<br />
        /// return 0.CombineHashCode(field1).CombineHashCode(field2).
        ///     CombineHashCode(field3);
        /// </summary>
        public static int CombineHashCode<T>(this int hashCode, T arg)
        {
            unchecked
            {
                return 31 * hashCode + arg.GetHashCode();
            }
        }
    }

}

Based on this answer from Jon Skeet (to my earlier question)

"What should I do if I change a property that ultimately changes the value of the key?" - Me

.

"You're stuffed, basically. You won't (or at least probably won't) be able to find that key again in your dictionary. You should avoid this as carefully as you possibly can. Personally I usually find that classes which are good candidates for dictionary keys are also good candidates for immutability." - J.S.

Does this mean that I need to remove the object from the Dictionary and re add it? Is this the proper / best way?

Was it helpful?

Solution

Okay, so to clarify: you're modifying the key part of the key/value pair.

Now that the question's clear, the answer is relatively easy:

Does this mean that I need to remove the object from the Dictionary and re add it?

Yes. But - you've got to remove it before you modify it. So you'd write:

testDictionary.Add(keyValue, "some data");
// Do whatever...

testDictionary.Remove(keyValue);
te.EntryName = "modified data";
testDictionary.Add(keyValue, "some data"); // Or a different value...

In general though, it would be far less risky to only use immutable data structures as dictionary keys.

Also note that currently your Equals method relies on reference equality of the two lists involved - is that really what you want? Also, you're not overriding GetHashCode in TrustedEntity, so even if you did create a new TrustedEntity with the same lists, it wouldn't give you the result you want. Basically, it's unclear what sort of equality operation you want - you need to clarify that to yourself, and then ideally create an immutable representation of the data involved.

OTHER TIPS

The question of whether GetHashCode() should change is a bit of a red herring. I would suggest six axioms:

  1. Every object should always be observed to be equal to itself.
  2. If one object has ever been observed to be equal to another, both objects should forever more report themselves equal to each other.
  3. If one object has ever been observed to be unequal to another, both objects should forever more report themselves unequal to another.
  4. If one object has ever been observed to be equal to another, and either is observed to be equal to a third, both should forever more report themselves equal to that third object.
  5. If one object has ever been observed to be equal to another, and either is observed to be unequal to a third, both should forever more report themselves unequal to that third object.
  6. An observation of an object's hash code represents an observation that it is unequal to every object that has ever returned a different hash code.

The requirement that an object's hash code not change is not one of the axioms, but derives from points #1 and #6; an observation of an object's hash code which differed from an earlier observation would constitute an observation that the object was unequal to itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top