Junior — Middle
What data types are permissible as keys when working with dictionaries?
sobes.tech AI
Answer from AI
In C#, dictionary keys (Dictionary<TKey, TValue>) can be any types that meet the following requirements:
- Implement a proper
Equalsmethod for equality comparison. - Implement the
GetHashCodemethod for hash code calculation.
This is necessary for the dictionary to efficiently store and search for elements.
Examples of valid keys:
- Primitive types (
int,string,Guid) - User-defined classes and structs, if
EqualsandGetHashCodeare overridden
Example of a user-defined key:
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);
}
}
var dict = new Dictionary<Person, string>();
dict[new Person { Name = "Alice", Age = 30 }] = "Developer";
If the key does not override these methods, the dictionary may not work correctly.