Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8703031
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T02:47:22+00:00 2026-06-13T02:47:22+00:00

I’ve asked this question recently a few different ways, but don’t get an answer

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T02:47:23+00:00Added an answer on June 13, 2026 at 2:47 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This could be a duplicate question, but I have no idea what search terms
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I've tracked down a weird MySQL problem to the two different ways I was
I know there's a lot of other questions out there that deal with this
I don't have much knowledge about the IPv6 protocol, so sorry if the question
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.