user2017341
user2017341

Reputation: 175

GetHashCode() - immutable values?

As I know the method "GetHashCode()" should use only readonly / immutable properties. But if I change for example id property which use GetHashCode() then I get new hash code. So why it should be immutable? If it wouldn't changed then I see problem but it changes.

class Program
{
    public class Point
    {
        public int Id { get; set; }

        public override bool Equals(object obj)
        {
            return obj is Point point &&
                    Id == point.Id;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Id);
        }
    }

    static void Main(string[] args)
    {
        Point point = new Point();
        point.Id = 5;

        var r1 = point.GetHashCode(); //467047723

        point.Id = 10;
        var r2 = point.GetHashCode(); //1141379410
    }
}

Upvotes: 0

Views: 834

Answers (2)

Postlagerkarte
Postlagerkarte

Reputation: 7127

GetHashCode() is there for mainly one reason: retrieval of an object from a hash table. You are right that it is desirable that the hash code should be computed only from immutable fields, but think about the reason for this. Since the hashcode is used to retrieve an object from a hashtable it will lead to errors when the hashcode changes while the object is stored in the hashtable.

To put it more generally: the value returned by GetHashCode must stay stable as long as a structure depends on that hashcode to stay stable. So for you example it means you can change the id field as long as the object is currently not used in any such structure.

Upvotes: 2

Ehsan K. harchegani
Ehsan K. harchegani

Reputation: 3128

Exactly because of this, because if it's not Immutable the hash code changes every time

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

so if it changes every time you can't use it for its purpose. more info...

Upvotes: 2

Related Questions