Sobes.tech
Middle

What data types can be used as keys for a dictionary in C#?

sobes.tech AI

Answer from AI

Any data types for which the Equals and GetHashCode methods are correctly implemented.

  • Value types (structs): By default, they implement Equals and GetHashCode based on their fields.
  • Reference types (classes): By default, they use reference comparison and hash code based on the object’s address. To use them as keys, you need to override Equals and GetHashCode so that they compare by value.
  • Immutable types (like string): They are good candidates because their value does not change, which guarantees the consistency of the hash code.
// A class that can be used as a key if you override Equals and GetHashCode
public class MyKey
{
    public int Id { get; set; }
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        // Null check and type casting
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        MyKey other = (MyKey)obj;
        // Compare by value of fields
        return (Id == other.Id) && (Name == other.Name);
    }

    public override int GetHashCode()
    {
        // Generate hash code based on fields
        // Use Tuple.GetHashCode() or bitwise operations
        return (Id, Name).GetHashCode();
    }
}