Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Why GetHashCode() matters?

I am trying to understand what the object.GetHashCode() is used for. I read that it is used by collections to uniquely identify keys. But I wanted to test this and the result isn't what I expected.

struct Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Animal(string name, int age) : this()
    {
        Name = name;
        Age = age;
    }

    public override int GetHashCode()
    {
        return Age.GetHashCode();
    }
}

object doggy = new Animal("Dog", 25);
object cat = new Animal("Cat", 25);

Hashtable table = new Hashtable();
table.Add(doggy, "Dog");
table.Add(cat, "Cat");

Console.WriteLine("{0}", table[cat]);
Console.WriteLine("{0}", table[doggy]);

I would have expected "Cat" would overwrite "Dog" or some kind of error telling me that the "key already exists" but the output is

"Cat" "Dog"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

GetHashCode is only the first check, used to determine non-equality and possible equality. After that, Equals is checked. Which for objects defaults to reference-equality, and for structs is a memberwise compare. Override Equals to give an appropriate implementation (paired with the hash-code), and it should give the results you expect (duplicate key).

btw, the IDE is probably already giving you a warning that GetHashCode and Equals should always be treated together...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...