namespace Dic
{
public class Key
{
string name;
public Key(string n) { name = n; }
}
class Program
{
static string Test()
{
Key a = new Key(
you problem is that
new Key("A").Equals(new Key("A"))==false.
and
new Key("A").GetHashCode()!=new Key("A").GetHashCode()
fix that and it should work I think. To fix it override the Equals method and check if the name values are the same. You should also override GetHashCode if you are overriding Equals.
ContainsKey in this case is comparing Key as objects and checking to see if the objects themselves are the same -- they are not. You need to implement IComparable or override Key.Equals or something along those lines to get it to do what you want.
they have the same values internally but a != b as they are 2 different variables.
You need to override the Equals
and GetHashCode
methods of your Key class. In your case you could compare based on the key's name (or on any other unique property if your class is more complex).
public class Key {
string name;
public Key(string n) { name = n; }
public override bool Equals(object obj) {
Key k = obj as Key;
if (k == null)
return false;
return name.Equals(k.name);
}
public override int GetHashCode() {
return name.GetHashCode();
}
}
Then you will need to override GetHashCode and Equals on the Key class.
Without doing that, you get the default implementation of both. Which results in the hashcode for a and b to be most likely not the same (I don't know how what the default implementation looks like), and a to be definitely not equal to b (the default Equals() implementation checks reference equality).
In your case, assuming "name" is not a null, it could be implemented as
public class Key
{
string name;
public override int GetHashCode()
{
return name.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
Key objAsKey = obj as Key;
if (objAsKey == null)
{
return false;
}
return this.name.Equals(objAsKey.Name);
}
}
Whether this is a satisfactory hash is a different story, but it shows the principle, nevertheless.
It would probably help if you override Key.GetHashCode and Key.Equals.
In Key
:
public override bool Equals(object obj)
{
var k = obj as Key;
if (k != null)
{
return this.name == k.name;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return this.name.GetHashCode();
}