Search code examples
c#dictionarynew-operatorequals

Dictonary.ContainsKey Comparison


I am trying to do something along the lines of the following:

class Test
{
     public string Name { get; set;}
     public string Location { get; set;}
     public Test(string name, string location)
     {
         Name = name;
         Location = location;
     }
}

Now, in a method in another class, I am trying to add these Test classes into a Dictionary with a KeyValuePair of

Dictionary<Test,int> resources = new Dictionary<Test,int>();
resources.Add(new Test("First Resource", "Home"), 1);

Now, what I am trying to do, and need to be able to do is:

bool contains = resources.ContainsKey(new Test("First Resource", "Home"));
resources[new Test("First Resource", "Home")] = 2;

As of now, this returns false. How can I get this to return true?

I have tried overriding the Equals function of my Test class and even implementing IComparible and doing custom comparisons.


Solution

  • You need to override GetHashCode in your Test class, add the following to your class:

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

    This will ensure that any two Test instances have the same hash only if the concatenation of Name and Location are the same. You could use other strategies for this, however, this is the simplest form.