Junior — Middle
How is the Equals method implemented when working with dictionaries and how does it affect data handling?
sobes.tech AI
Answer from AI
In C#, the Equals method is used to compare objects for equality. When working with dictionaries (Dictionary<TKey, TValue>), keys are compared using the Equals method and the GetHashCode hash function.
This means that for the dictionary to work correctly, it is important that:
- The
Equalsmethod is overridden so that logically equal keys are considered equal. - The
GetHashCodemethod returns the same value for equal keys.
If Equals is implemented incorrectly, the dictionary may not find existing keys or may allow duplicates, leading to errors when searching, adding, or removing elements.
Example of overriding Equals and GetHashCode:
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);
}
}