473,782 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic Collection with reference types

Hi,
I have just started using Generic Collections for .Net 2.0 and so far
they are working very nicely for me. But, I do have a couple of questions.
If I have a Generic collection which has a type which is a reference type,
is there a way to get Collection.Cont ainsKey(RefKey) and Collection[RefKey]
to work with different instances of equal keys?

For example, I have defined a class of "codon" and I have made a dictionary
private System.Collecti ons.Generic.Dic tionary<Codon, DoubleCodonUsag e;

I have two instances of CodonUsage and want to write codon similar to:
if (CodonUsageInst ance1[ThisCodon] == CodonUsageInsta nce2[ThisCodon])
{
Do Stuff;
}

but this doesn't work. I am pretty sure that it is because the two different
instances of Codon Usage were populated with different instances of Codons
and thus they don't contain entries for arbitrary Codons even if they do
contain entries for Codons which are identical. My definition for Codon does
have an override of equals, so that different instances will evaluate to
equals correctly. I have similar issues with .ContainsKey.

Any help would be appreciated.

Thanks!

Ethan

Ethan Strauss Ph.D.
Bioinformatics Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
et***********@p romega.com
Apr 23 '07 #1
5 1868
Ethan,

This isn't an issue which involves generics, but rather, you want your
object identity to be defined by properties on the object, and not the
object reference, which it is by default.

You need to do two things. The first thing is to override the Equals
method in your Codon class so that it will compare an instance of the Codon
class to another that is passed to it, and determine, based on the values,
if they are the same or not.

The second thing you do is you need to override GetHashCode so that it
returns a value that is based on the hash of the values that your Codon
class is comparing for equality against. In other words, if you have a
field that is a string and a field that is an integer, then you need to
generate a hash code that is based on those two fields (assuming they are
used to test equality). You easily find hash code implementations through
google.

Once that is done, you should be able to use different instances of your
Codon class as keys in your dictionary, but have the same values, and get
the same results.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ethan Strauss" <ethan dot strauss at Promega dot comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi,
I have just started using Generic Collections for .Net 2.0 and so far
they are working very nicely for me. But, I do have a couple of questions.
If I have a Generic collection which has a type which is a reference type,
is there a way to get Collection.Cont ainsKey(RefKey) and
Collection[RefKey] to work with different instances of equal keys?

For example, I have defined a class of "codon" and I have made a
dictionary
private System.Collecti ons.Generic.Dic tionary<Codon, DoubleCodonUsag e;

I have two instances of CodonUsage and want to write codon similar to:
if (CodonUsageInst ance1[ThisCodon] == CodonUsageInsta nce2[ThisCodon])
{
Do Stuff;
}

but this doesn't work. I am pretty sure that it is because the two
different instances of Codon Usage were populated with different instances
of Codons and thus they don't contain entries for arbitrary Codons even if
they do contain entries for Codons which are identical. My definition for
Codon does have an override of equals, so that different instances will
evaluate to equals correctly. I have similar issues with .ContainsKey.

Any help would be appreciated.

Thanks!

Ethan

Ethan Strauss Ph.D.
Bioinformatics Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
et***********@p romega.com


Apr 23 '07 #2
<"Ethan Strauss" <ethan dot strauss at Promega dot com>wrote:
I have just started using Generic Collections for .Net 2.0 and so far
they are working very nicely for me. But, I do have a couple of questions.
If I have a Generic collection which has a type which is a reference type,
is there a way to get Collection.Cont ainsKey(RefKey) and Collection[RefKey]
to work with different instances of equal keys?

For example, I have defined a class of "codon" and I have made a dictionary
private System.Collecti ons.Generic.Dic tionary<Codon, DoubleCodonUsag e;

I have two instances of CodonUsage and want to write codon similar to:
if (CodonUsageInst ance1[ThisCodon] == CodonUsageInsta nce2[ThisCodon])
{
Do Stuff;
}
You're not making a lot of sense - you're talking about "instances" of
CodonUsage, but it's a variable, not a type.

Have you overridden GetHashCode as well as Equals, by the way?

--
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
Apr 23 '07 #3
"Ethan Strauss" <ethan dot strauss at Promega dot comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi,
I have just started using Generic Collections for .Net 2.0 and so
far they are working very nicely for me. But, I do have a couple of
questions. If I have a Generic collection which has a type which is a
reference type, is there a way to get Collection.Cont ainsKey(RefKey)
and Collection[RefKey] to work with different instances of equal keys?

For example, I have defined a class of "codon" and I have made a
dictionary
private System.Collecti ons.Generic.Dic tionary<Codon, Double>
CodonUsage;

I have two instances of CodonUsage and want to write codon similar to:
if (CodonUsageInst ance1[ThisCodon] == CodonUsageInsta nce2[ThisCodon])
{
Do Stuff;
}
<snip>
OK perhaps I'm being particularly dense tonight since Jon and Nicholas
have already replied and haven't mentioned it but here goes.

I think your problem is that you are attempting to compare 2 doubles
using ==, and that is a no-no.

Bill



Apr 24 '07 #4
Thanks to all.
Overriding GetHashCode was what I was missing. That did the trick.
Do any of you have the time/desire to explain what GetHashCode is used
for? Is there anything out there that really explains the guts of
collections and how all the bits and pieces work?
Thanks again,
Ethan

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in
message news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
Ethan,

This isn't an issue which involves generics, but rather, you want your
object identity to be defined by properties on the object, and not the
object reference, which it is by default.

You need to do two things. The first thing is to override the Equals
method in your Codon class so that it will compare an instance of the
Codon class to another that is passed to it, and determine, based on the
values, if they are the same or not.

The second thing you do is you need to override GetHashCode so that it
returns a value that is based on the hash of the values that your Codon
class is comparing for equality against. In other words, if you have a
field that is a string and a field that is an integer, then you need to
generate a hash code that is based on those two fields (assuming they are
used to test equality). You easily find hash code implementations through
google.

Once that is done, you should be able to use different instances of
your Codon class as keys in your dictionary, but have the same values, and
get the same results.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ethan Strauss" <ethan dot strauss at Promega dot comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>Hi,
I have just started using Generic Collections for .Net 2.0 and so far
they are working very nicely for me. But, I do have a couple of
questions. If I have a Generic collection which has a type which is a
reference type, is there a way to get Collection.Cont ainsKey(RefKey) and
Collection[RefKey] to work with different instances of equal keys?

For example, I have defined a class of "codon" and I have made a
dictionary
private System.Collecti ons.Generic.Dic tionary<Codon, DoubleCodonUsag e;

I have two instances of CodonUsage and want to write codon similar to:
if (CodonUsageInst ance1[ThisCodon] == CodonUsageInsta nce2[ThisCodon])
{
Do Stuff;
}

but this doesn't work. I am pretty sure that it is because the two
different instances of Codon Usage were populated with different
instances of Codons and thus they don't contain entries for arbitrary
Codons even if they do contain entries for Codons which are identical. My
definition for Codon does have an override of equals, so that different
instances will evaluate to equals correctly. I have similar issues with
.ContainsKey .

Any help would be appreciated.

Thanks!

Ethan

Ethan Strauss Ph.D.
Bioinformati cs Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
et***********@p romega.com



Apr 24 '07 #5
<"Ethan Strauss" <ethan dot strauss at Promega dot com>wrote:
Overriding GetHashCode was what I was missing. That did the trick.
Do any of you have the time/desire to explain what GetHashCode is used
for? Is there anything out there that really explains the guts of
collections and how all the bits and pieces work?
The basic idea is that code is a quick way of narrowing down *possible*
matches, e.g. for keys in a hashtable.

Two keys which are equal should *definitely* have the same hashcode,
but two keys which aren't equal *might* have the same hashcode. In an
ideal world, hashcodes should be distributed such that two unequal keys
will almost always have different hashcodes.

When you look up a key in a hashtable, it first finds all the elements
with the right hashcode. After that it asks each of those whether or
not it's equal to the key you've passed in.

--
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
Apr 24 '07 #6

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

Similar topics

18
3051
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
2
2515
by: Edward Diener | last post by:
In C++ an overridden virtual function in a derived class must have the exact same signature of the function which is overridden in the base class, except for the return type which may return a pointer or reference to a derived type of the base class's return type. In .NET the overridden virtual function is similar, but an actual parameter of the function can be a derived reference from the base class's reference also. This dichotomy...
8
1833
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
22
13124
by: Adam Clauss | last post by:
OK, I have class A defined as follows: class A { A(Queue<B> queue) { ... } } Now, I then have a subclass of both classes A and B. The subclass of A (SubA), more specifically is passed a Queue<SubB>.
8
3283
by: Steven Cummings | last post by:
Hello, I've scoured this usenet group and didn't find anything specific to my problem, so hopefully this won't be a repeated question. I'm all but certain it's not. I would like to *declare* (not just instantiate at runtime) a generic collection whose element-type is a generic class too. But I don't want to declare what the element-type's generic parameters are.
1
2504
by: Semmel | last post by:
Hello, I'd like to use the C5 Generic Collection Library ( http://www.itu.dk/research/c5/ ) in my C++/CLI project. However I always get an fatal compiler error C1001. It already happens when you just add the two obvious lines to the CLR-console type wizard generated main method: #include "stdafx.h" #using <C5.dll // <---- this line is new
7
2845
by: =?Utf-8?B?Sm9lbCBNZXJr?= | last post by:
I have created a custom class with both value type members and reference type members. I then have another custom class which inherits from a generic list of my first class. This custom listneeds to support cloning: Public Class RefClass Public tcp As TcpClient Public name As String End Class Public Class RefClassList Inherits List(Of RefClass) Implements ICloneable
26
3630
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic delegate type expression in just the right place and a well-named method means we can almost read the code out loud and understand it without even thinking. Note that since 'boxing' and 'unboxing' is involved (I think), you don't get what you...
2
4185
by: SimonDotException | last post by:
I am trying to use reflection in a property of a base type to inspect the properties of an instance of a type which is derived from that base type, when the properties can themselves be instances of types derived from that base type, or arrays or generic collections of instances of types derived from that base type. All is well until I come to the properties which are generic collections, I don't seem to be able to find an elegant way of...
0
9639
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
9479
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10146
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
10080
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
9942
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
6733
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
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
4043
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
3
2874
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.