Junior — Middle
What steps are necessary to use a custom class as a key in a dictionary-like collection?
sobes.tech AI
Answer from AI
To use a custom class as a key in a dictionary (Dictionary<TKey, TValue>) in C#, you need to ensure proper comparison of keys and calculation of their hash codes. To do this:
- Override the
Equals(object obj)method so that it correctly compares your class objects based on meaningful fields. - Override the
GetHashCode()method so that objects considered equal have the same hash code.
Example:
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);
}
}
Alternatively, you can implement the IEqualityComparer<T> interface and pass it to the dictionary constructor if you prefer not to modify the class itself.