473,883 Members | 1,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<KeyC lass, stringmyDic = new
Dictionary<KeyC lass, 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<KeyC lass>
{
public string[] id;
public string name;

public KeyClass(string[] id, string name) {
this.id = id;
this.name = name;
}

public bool Equals(KeyClass other)
{
Console.WriteLi ne("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.IEquatab le 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 3682
Hi Kim,

Change it to:

bool IEquatable<KeyC lass>.Equals(Ke yClass other)
{
Console.WriteLi ne("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*********@gma il.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<KeyC lass, stringmyDic = new
Dictionary<KeyC lass, 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<KeyC lass>
{
public string[] id;
public string name;

public KeyClass(string[] id, string name) {
this.id = id;
this.name = name;
}

public bool Equals(KeyClass other)
{
Console.WriteLi ne("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.IEquatab le 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<KeyC lass>.Equals(Ke yClass other)
{
Console.WriteLi ne("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*********@gma il.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<KeyC lass, stringmyDic = new
Dictionary<KeyC lass, 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<KeyC lass>
{
public string[] id;
public string name;

public KeyClass(string[] id, string name) {
this.id = id;
this.name = name;
}

public bool Equals(KeyClass other)
{
Console.WriteLi ne("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.IEquatab le 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*********@gm ail.comwrote in message
news:11******** **************@ 48g2000cwx.goog legroups.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<KeyC lass, stringmyDic = new
Dictionary<KeyC lass, 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<KeyC lass>
{
public string[] id;
public string name;

public KeyClass(string[] id, string name) {
this.id = id;
this.name = name;
}

public bool Equals(KeyClass other)
{
Console.WriteLi ne("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.IEquatab le 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<KeyC lass>
{
///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.GetHashCod e() ^ id[0].GetHashCode();
}
public override bool Equals(object obj)
{
///just test the type and call IEquatable<T>.E quals
KeyClass other = obj as KeyClass;
if (other == null)
return false;

return Equals(other);
}

public bool Equals(KeyClass other)
{
System.Diagnost ics.Trace.Write Line("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
1984
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 relational databases except at the table column level. I am working on some Python which would hopefully give me a form of generic access to more common data dictionary functionality such as indices, constraints etc. but no such functionality...
125
7285
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
15961
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 comment 1). However, if I attempt to access the dictionary by using a key object that
1
2470
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 matches the key in the dictionary to an index in the collection? dan Here is the code i want to add IList to. public interface ISystemMessageData
18
14983
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 expensive is it to instantiate/use Generic Dictionaries in great numbers (let's just say 100000's ), in terms of memoryuse and performance? Any practical experiences out there?
3
11778
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 : IXmlSerializable {
0
971
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 collections. I want to wrap a System.Collections.Generic.Dictionary. The wrapping class should have a constructor similar to that of the dictionary (besides some possible other argument). Intuitively I want something "like":
2
10710
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
4188
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
9942
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 usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
11148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10749
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10419
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5801
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4618
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
2
4223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3236
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.