473,573 Members | 3,267 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

am i using the dictinalry generic class correctly?

hi..

i wanted to build a Dictionary Classs that will load my own class
called letter,
i understood that i implement the IEquatable interface's equles method
that then the dictionary would use that inorder to compare the keys, so
i went ahead the implented it in the LETTER class so letter would
provice it's own means for comparison, but the dictionary ignored it

only when i created a new class, called it letterkey ,had it implement
EqualityCompare r that will compare to classes , have it's GetHashCode
always return 0, only i managed to compare the two classes.

is that right? that's the only way i got it to work.

so now i have:

Dictionay<Lette r,Letter> letters= new Dictionay<Lette rs,Letters>(new
LetterKey())

Jan 22 '06 #1
12 1843
Elhanan <em*****@hotmai l.com> wrote:
hi..

i wanted to build a Dictionary Classs that will load my own class
called letter,
i understood that i implement the IEquatable interface's equles method
that then the dictionary would use that inorder to compare the keys, so
i went ahead the implented it in the LETTER class so letter would
provice it's own means for comparison, but the dictionary ignored it


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

Here's some example code which *does* work:

using System;
using System.Collecti ons.Generic;

class Letter : IEquatable<Lett er>
{
char value;

public Letter(char value)
{
this.value = value;
}

public bool Equals(Letter other)
{
Console.WriteLi ne ("Equals called");
return other.value==va lue;
}
}

class Test
{
static void Main()
{
Dictionary<Lett er,Letter> map= new Dictionary<Lett er,Letter>();

Letter c = new Letter('c');
map[c]=c;
Console.WriteLi ne (map[c]==c);
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 22 '06 #2
Elhanan,

You need to have the IEquatable interface implementation return a hash
code. If you don't have it return a hash code for the instances passed in,
then you are pretty much killing the efficiency of the hash table. Since
all of the keys will return the same hashcode, only one bucket will be used,
and you will have to loop through all of the items to find the key.

Why not just return the hash value of the instances that are passed in?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Elhanan" <em*****@hotmai l.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
hi..

i wanted to build a Dictionary Classs that will load my own class
called letter,
i understood that i implement the IEquatable interface's equles method
that then the dictionary would use that inorder to compare the keys, so
i went ahead the implented it in the LETTER class so letter would
provice it's own means for comparison, but the dictionary ignored it

only when i created a new class, called it letterkey ,had it implement
EqualityCompare r that will compare to classes , have it's GetHashCode
always return 0, only i managed to compare the two classes.

is that right? that's the only way i got it to work.

so now i have:

Dictionay<Lette r,Letter> letters= new Dictionay<Lette rs,Letters>(new
LetterKey())

Jan 22 '06 #3
IEquatable does not have a GetHashCode method, iEqualityCompar aor does,
however when i simply returned the hash of the instance, i never got an
exception of a duplicatekey on the add method when i added to objects
which had the same key properties, which should make sense becoue each
object did have a different hashcode.

Jan 23 '06 #4
i didn't try to test the equality of the objects what is this:

Lettter l =new Letter (....)
Letter l2 =new (Letter(...) // same constructor datra

Dictionary<Lett er,Letter> map= new Dictionary<Lett er,Letter>();

map.add(l);
map.add(l2); // should a duplicae key exception here but didn''t.

Jan 23 '06 #5

"Elhanan" <em*****@hotmai l.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
IEquatable does not have a GetHashCode method, iEqualityCompar aor does,
however when i simply returned the hash of the instance, i never got an
exception of a duplicatekey on the add method when i added to objects
which had the same key properties, which should make sense becoue each
object did have a different hashcode.


I'm having trouble understanding you on this but note a few things:

1) If your class has a "standard" meaningful concept of equality then it
should
probably implement IEquatable and it should definitely override
Object.Equals and Object.GetHashC ode such that if a.Equals(b) then
a.GetHashCode() == b.GetHashCode() . If 2 keys are "Equals()" but have
different hash codes then no hashtable will see them as being equal since
the comparison is essentially "a.GetHashCode( ) == b.GetHashCode() &&
a.Equals(b)" in that order.

2) If you do not give a good hashcode your dictionary/hashtable performance
will suck. In particular; If you return a constant value you will end up
doing linear searches of a linked list.

3) IEqualityCompar er is should not be implemented by the target class itself
but by another class as it is intended for comparisons other than "normal".
For example Person.Equals would probably compare first and last names but
you might want a customer comparer that only compared surname. Sometime it
makes sense for a class to make a comparer available as a convenience using
a static method eg. Person.GetSurna meComparer()
Jan 23 '06 #6
ok as it stands my class does not implement IEquatable (actually i
think it does but it's not being used i think i'll drop it from what
you said).. it does not override GetHasCode or Object.Equels

in my case 2 letters are considered the same of certain group of their
properties are the same (but not all) for this i created a new class
callled letterkey that imlements iEqualityCompar aor and overrode all
it's methodls, in it's compare method, i did the compare between the
classes and return true in case all of the properties i'm interested
are the same.
in it's GetHashCode i always return 0 becouse otherwise the Equels
method would never get called, so i have no choice.

Jan 23 '06 #7
Elhanan wrote:
ok as it stands my class does not implement IEquatable (actually i
think it does but it's not being used i think i'll drop it from what
you said).. it does not override GetHasCode or Object.Equels

in my case 2 letters are considered the same of certain group of their
properties are the same (but not all) for this i created a new class
callled letterkey that imlements iEqualityCompar aor and overrode all
it's methodls, in it's compare method, i did the compare between the
classes and return true in case all of the properties i'm interested
are the same.
in it's GetHashCode i always return 0 becouse otherwise the Equels
method would never get called, so i have no choice.


You do have a choice - return a value which will always be the same for
any two objects which will compare positively for equality. There are
plenty of ways of doing that, usually involving combining the hashcodes
of the properties you compare in the equality comparison.

If you're just returning 0 for all the hash codes, you should just use
a list instead...

Jon

Jan 23 '06 #8
ok i looked at the help some more and this what i did:

i overode my GetHashCode method in my function and implemented so it
would return all the properties with xor operator between them (most of
my properties are int anway, and one is date and the other is decima,
so for them i simply used their getHasCode method), it then implemented
IEquatable interface in my letter like so:
public bool Equals(Letter source)
{
return this.GetHashCod e() == source.GetHashC ode();
}

so now i don't think i need another class, i still get an actuall has
function right?

Jan 24 '06 #9
Elhanan <em*****@hotmai l.com> wrote:
ok i looked at the help some more and this what i did:

i overode my GetHashCode method in my function and implemented so it
would return all the properties with xor operator between them (most of
my properties are int anway, and one is date and the other is decima,
so for them i simply used their getHasCode method), it then implemented
IEquatable interface in my letter like so:
public bool Equals(Letter source)
{
return this.GetHashCod e() == source.GetHashC ode();
}

so now i don't think i need another class, i still get an actuall has
function right?


Well, firstly I wouldn't implement your hash code like that. A quick
and reasonable hash code is obtained using something like:

int ret = 17;
ret = 37*ret + FirstProperty.G etHashCode();
ret = 37*ret + SecondProperty. GetHashCode();
// etc
return ret;

The advantage of that over using XOR is this: Suppose you have two ints
in your object. If they have the same value, when they are XORed
together that result is 0 *whatever the value is*. In other words,
although they are different, they get the same hash code. Now, this
isn't fatal, but it doesn't make for a great hash code.
Secondly, your Equals method is broken - it will return true for
comparisons where the hash codes are the same but the objects are
different. There's nothing to say a hash code has to be unique, and
indeed very few are. You should compare your properties, just as you
did before.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 24 '06 #10

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

Similar topics

7
2361
by: Allan Bruce | last post by:
I have had a look through the FAQ and found that if I am using a class template then I need an argument list. I have tried to add this but it is not quite working - i.e. it doesnt compile. My code is below, could somebody please point me in the right direction? Thanks Allan #include <iostream>
121
9975
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather...
9
3946
by: Guy | last post by:
I have extended the datetimepicker control to incorporate a ReadOnly property. I have used the new keyword to implement my own version of the value property, so that if readonly == true then it will not set the value of the control and will leave the checked status of the checkbox to false when a user selects a new date. this works fine...
2
15911
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 find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code...
15
5316
by: David Lozzi | last post by:
Howdy, I have a function that uploads an image and that works great. I love ..Nets built in upload, so much easier than 3rd party uploaders! Now I am making a public function that will take the path of the uploaded image, and resize it with the provided dimensions. My function is below. The current function is returning an error when run...
1
5358
by: cesco | last post by:
Hi, I'm using the boost library program_options for parsing the command line given to my program as described in the class Parameter: // Main.cpp #include "Parameter.h" using namespace std; int main(int ac, char* av)
1
2020
by: colinjack | last post by:
Hi All, I've been using the original (non-event based) asynchronous design pattern using delegates. It works fine but performance wise I know using the ThreadPool is supposed to be far better, so I wondered if anyone had any examples of the best way to do this. I've obviously had a look myself but haven't gotten very far and although...
0
5919
by: crazyone | last post by:
I've got a gaming framework i'm building and i want to save myself the trouble of reading and writting the complete game data to a custom file and load/save it to an XML file but i'm getting problem serializing my stuff to XML when it comes to collections. I'm currently using .net2 with generic lists to prevent users putting all sorts of...
6
2139
by: greek_bill | last post by:
Hi, I'm interested in developing an application that needs to run on more than one operating system. Naturally, a lot of the code will be shared between the various OSs, with OS specific functionality being kept separate. I've been going over the various approaches I could follow in order to implement the OS-specific functionality. The...
0
7741
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7661
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
6347
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5252
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3692
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2163
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1256
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
984
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.