A
A
Anton Fedoryan2016-01-13 14:23:05
.NET
Anton Fedoryan, 2016-01-13 14:23:05

How to override Object.GetHashCode()?

How can I override the GetHashCode() method when using a dictionary?
I am reading this :

The type used as the dictionary key must override the GetHashCode() method of the Object class.

The key will be a string. I found the necessary algorithm for generating a hash, but I don’t understand how to substitute it.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2016-01-13
@GavriKos

If your key is a string, i.e. string type - nothing needs to be redefined. string already has GetHashCode implemented.

P
Peter, 2016-01-13
@petermzg

Override in your class

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

A
Alexey Pavlov, 2016-01-13
@lexxpavlov

if your key is a string, then take the hash of the string:

class Test
{
    public string Name;

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

But usually you also need to redefine Equals.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question