473,320 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Dictionary Generic Class

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".

Any alternative idears how to make the example work (getting an
exception trying to add the same key twice)?

Jan 2 '07 #1
3 3655
Hi Kim,

Change it to:

bool IEquatable<KeyClass>.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;
}

Regards,
Valentin Ivanov.
ki*********@gmail.com wrote:
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".

Any alternative idears how to make the example work (getting an
exception trying to add the same key twice)?
Jan 2 '07 #2
Hello Kim,

Please disregard my previous e-mail.
The reason why your Equals method is not called is because internally
default comparer checks hash code first and then it calls Equals
method.

In your case you have 2 completely different instances. Each will have
its own different hash code. So the first check of hash codes will
return false which will be enough for dictionary to create new entry.

Try overload GetHashCode() method of your KeyClass and you'll see what
I mean

public override int GetHashCode()
{
return 0; //this will return same hash code for all
instances of the KeyClass
}

Regards,
Valentin Ivanov.
Architect wrote:
Hi Kim,

Change it to:

bool IEquatable<KeyClass>.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;
}

Regards,
Valentin Ivanov.
ki*********@gmail.com wrote:
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".

Any alternative idears how to make the example work (getting an
exception trying to add the same key twice)?
Jan 2 '07 #3


<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

Jan 2 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Edward Diener | last post by:
Version 2.0 of the Python database API was written over 5 years ago, in 1999. While it has been used successfully by many implementations, there is no generic access into the data dictionary of...
125
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
2
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to...
1
by: Dan Holmes | last post by:
I have a custom dictionary and i would like to bind it to a control. Since Dictionary doesn't implement IList i would have to write it. Is the only way to do this to keep another collection that...
18
by: Rune B | last post by:
Hi Group I was considering using a Generic Dictionary<> as a value container inside my business objects, for the reason of keeping track of fields changed or added and so on. - But how...
3
by: fstorck | last post by:
Hi, I'm kind of stuck with an serializing / deserializing problem using a generic dictionary holding references to various generic types. It goes as follows: <code> class MyBase :...
0
by: pamela fluente | last post by:
Wrapping the old classic collections was straightforward. But with System.Collections.Generic we have that particular constructor (Of SomeType...) and I am not clear how I can wrap these typed...
2
by: Stephen Costanzo | last post by:
I have: Public Class test Private displayValue As String Private dbType As Integer Property Display() As String Get Return displayValue End Get
3
by: wildThought | last post by:
If I have an object that contains a generic dictionary inside of it, how do I get access to its properties such as count?
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.