K
kim.nolsoee
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, string> myDic = 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".
Any alternative idears how to make the example work (getting an
exception trying to add the same key twice)?
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, string> myDic = 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".
Any alternative idears how to make the example work (getting an
exception trying to add the same key twice)?