Why is it important to override GetHashCode when overriding Equals in C#?
Hello everyone! I'm a beginner C# developer, and I'm confused about the Equals and GetHashCode methods.
I created a simple `Person` class with `Name` and `Age` fields. I need two objects to be considered equal if they have the same values for these fields. So I overrode the `Equals` method:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
Person other = (Person)obj;
return Name == other.Name && Age == other.Age;
}
}
```
Everything works fine when I compare objects directly: `person1.Equals(person2)` returns `true` for identical data. But when I tried to use it in a