Sobes.tech
Junior — Middle

What is the role of the Equals method when working with keys in a Dictionary collection?

sobes.tech AI

Answer from AI

The Equals method in C# is used to determine the equality of objects. In the Dictionary collection, it plays a key role in comparing keys to determine if such keys already exist in the dictionary. If two keys are considered equal by Equals, they are regarded as the same element, and the value will be updated.

It is important that the key class correctly overrides the Equals and GetHashCode methods, otherwise the Dictionary may not work correctly.

Example of overriding:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Person other)
            return Name == other.Name && Age == other.Age;
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
}