<ki*********@gmail.comwrote in message
news:11**********************@48g2000cwx.googlegro ups.com...
Hi
I want to use the Dictionary Classs that will load my own class
called KeyClass used as TKey.
Here is the code:
public class Dictionary
{
public static void Main()
{
Dictionary<KeyClass, stringmyDic = new
Dictionary<KeyClass, string>();
KeyClass kc1 = new KeyClass(new string[]{ "1", "2", "3" },
"1");
KeyClass kc2 = new KeyClass(new string[]{ "1", "2", "3" },
"1");
myDic.Add(kc1, "1");
myDic.Add(kc2, "1");
}
}
class KeyClass : IEquatable<KeyClass>
{
public string[] id;
public string name;
public KeyClass(string[] id, string name) {
this.id = id;
this.name = name;
}
public bool Equals(KeyClass other)
{
Console.WriteLine("Equals called");
if(other.name==name && other.id[0] ==id[0] && other.id[1]
==id[1] && other.id[2] ==id[2])
return true;
else
return false;
}
}
I do not understand why KeyClass.Equals does not get called .
To my understanding the documentation
(http://msdn2.microsoft.com/en-us/library/xfhwa508.aspx) states that
"If TKey implements the system.IEquatable generic interface, the
default equality comparer uses that implementation".
IEquatable is a supplement to, not a replacement of, the normal method of
controlling object equality comparison. You should still override
GetHashCode() and Equals(object).
Your particular problem is a result of not overloading GetHashCode(). The
Dictionary first gets the hash code for the two keys, and since the hash
codes are different, it never has to run the Equals method for comparison.
You should also overload the non-generic Equals(object) method so the
comparison behaves the same whether you use a KeyObject reference or an
Object reference.
EG
sealed class KeyClass : IEquatable<KeyClass>
{
///make this an immutable class since we're
///relying on the field values to generate a hash code
public readonly string[] id;
public readonly string name;
public KeyClass(string[] id, string name)
{
this.id = id;
this.name = name;
}
public override int GetHashCode()
{
/// use the hash codes from the fields
/// to generate a reasonable hash for this object.
return name.GetHashCode() ^ id[0].GetHashCode();
}
public override bool Equals(object obj)
{
///just test the type and call IEquatable<T>.Equals
KeyClass other = obj as KeyClass;
if (other == null)
return false;
return Equals(other);
}
public bool Equals(KeyClass other)
{
System.Diagnostics.Trace.WriteLine("Equals called");
if (other.name == name && other.id[0] == id[0] && other.id[1] == id[1]
&& other.id[2] == id[2])
return true;
else
return false;
}
}
David