Junior — Middle
What is the result of calling the GetHashCode method on an object in .NET?
sobes.tech AI
Answer from AI
The GetHashCode method in .NET returns an integer value (hash code) that is used for quick comparison of objects, for example, when stored in hash tables (Dictionary, HashSet). By default, it is generated based on the internal state of the object, but it can be overridden to ensure correct behavior in collections and when comparing objects.
Example of overriding GetHashCode together with Equals:
public 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);
}
}
It is important that objects considered equal by Equals have the same hash code.