1. Override Equals, Get Hash Code, and the '==' Operator.
The Key class must override Equals
in order for the Dictionary to detect if they are the same. The default implementation is going to check references only.
Here:
public bool Equals(Key other)
{
return this == other;
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is Key))
{
return false;
}
return this.Equals((Key)obj);
}
public static bool operator ==(Key k1, Key k2)
{
if (object.ReferenceEquals(k1, k2))
{
return true;
}
if ((object)k1 == null || (object)k2 == null)
{
return false;
}
return k1.name == k2.name;
}
public static bool operator !=(Key k1, Key k2)
{
if (object.ReferenceEquals(k1, k2))
{
return false;
}
if ((object)k1 == null || (object)k2 == null)
{
return true;
}
return k1.name != k2.name;
}
public override int GetHashCode()
{
return this.name == null ? 0 : this.name.GetHashCode();
}
2. If Possible, use a struct.
You should use a struct for immutable datatypes like this, since they are passed by value. This would mean that you coulnd't accidentally munge two different values into the same key.