473,405 Members | 2,310 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,405 software developers and data experts.

ContainsKey() does not find key

I need to create object cache in memory.

Each object id can be composed from several string, integer and decimal type
values.

ContainsKey does not find existing key in this case.

How to force ContainsKey to compare object contents and find key?

Should i use Binaryformatter to serialize CacheKey, overload CacheKey ==
operator or any other idea ?

Andrus.
To reproduce,

run the code.

Observed:

Key not found

Expected:

Key found
using System.Collections.Generic;

class test {
struct CacheKey {
object Key;
public CacheKey(object key) {
Key = key;
}
}

static Dictionary<CacheKey, objectCache =
new Dictionary<CacheKey, object>();

static void Main() {
CacheKey key = new CacheKey(new object[] { "test1", 1 });
Cache.Add(key, "");
CacheKey key2 = new CacheKey(new object[] { "test1", 1 });
if (!Cache.ContainsKey(key2))
System.Windows.Forms.MessageBox.Show("Key not found");
else
System.Windows.Forms.MessageBox.Show("Key found");
}
}

Jun 25 '07 #1
6 10615
"Andrus" <ko********@hot.eewrote in message
news:eq**************@TK2MSFTNGP05.phx.gbl...
How to force ContainsKey to compare object contents and find key?

Should i use Binaryformatter to serialize CacheKey, overload CacheKey ==
operator or any other idea ?
In your class CacheKey, you have to override the method Equals that you
inherit from System.Object. Otherwise, Equals (which is being called by
ContainsKey to find your key) defaults to ReferenceEquals, which will return
false for the two objects that you use in your example since they are
different references.

When overriding Equals, you should also override the GetHashCode method
so that it returns the same code for two objects that are considered equal.
Jun 25 '07 #2
On Jun 25, 12:25 pm, "Andrus" <kobrule...@hot.eewrote:
I need to create object cache in memory.

Each object id can be composed from several string, integer and decimal type
values.

ContainsKey does not find existing key in this case.

How to force ContainsKey to compare object contents and find key?
By overriding Equals and GetHashCode, basically. If you implement
IEquatable<CacheKeyyou'll be saved the boxing penalty too (IIRC).

Out of interest, do you have any particular reason to make CacheKey a
struct rather than a class?

Jon

Jun 25 '07 #3
"Alberto Poblacion" <ea******************************@poblacion.orgwro te
in message news:eo**************@TK2MSFTNGP05.phx.gbl...
"Andrus" <ko********@hot.eewrote in message
news:eq**************@TK2MSFTNGP05.phx.gbl...
>How to force ContainsKey to compare object contents and find key?

Should i use Binaryformatter to serialize CacheKey, overload CacheKey ==
operator or any other idea ?

In your class CacheKey, you have to override the method Equals that you
inherit from System.Object. Otherwise, Equals (which is being called by
ContainsKey to find your key) defaults to ReferenceEquals, which will
return false for the two objects that you use in your example since they
are different references.
Key is object.
Usually it contains object (string, integer) array but class designer can
implement it differently.

How to override object Equals method in this case ?

Or should I require that object key contains object array always ?
When overriding Equals, you should also override the GetHashCode method
so that it returns the same code for two objects that are considered
equal.
This seems to be sophisticated.
Maybe it is simpler use string key and to serialize object to strin using
BinaryFormatter ?

Will Equals work propery with string keys ?

Andrus.

Jun 25 '07 #4
>How to force ContainsKey to compare object contents and find key?
>
By overriding Equals and GetHashCode, basically.
This seems to complicated (I'm new to C#). Where to find sample of this ?

Or is it simpler to override ToString() method and use string as distionary
key ?

>If you implement
IEquatable<CacheKeyyou'll be saved the boxing penalty too (IIRC).
I don't understand this.
Out of interest, do you have any particular reason to make CacheKey a
struct rather than a class?
I my real application I hold also object type in this structure:

struct CacheKey {
Type ObjectType;
object ID;

public CacheKey(Type objectType, object id) {
ObjectType = objectType;
ID = id;
}
}

ObjectType holds business object type : typeof(Customer) etc.
Otherwise different objects may suddenly have same keys.

Is this best approcach ?

Andrus.

Jun 25 '07 #5
add this to cache object Cache.Add(key2, 1);
Jun 26 '07 #6
On Jun 26, 2:03 pm, vijaya wrote:
add this to cache object Cache.Add(key2, 1);
But the point was to find that key2 was already in the cache, by
equality. The reason it's not working as intended is that the equality
and hashcode operations haven't been set up.

Jon

Jun 26 '07 #7

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

Similar topics

0
by: Dirk Försterling | last post by:
Hi all, a few days ago, I upgraded from PostgreSQL 7.2.1 to 7.4, following the instructions in the INSTALL file, including dump and restore. All this worked fine without any error (message). ...
5
by: Barry Anderberg | last post by:
I'm using a tool by Sci-Tech called the .NET Memory Profiler. We have a massive .NET/C# application here and it has been exhibiting memory leak behavior for some time. Attempting to remedy the...
13
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
3
by: Daniel Wilson | last post by:
LaborPool *Simulator::Controller::GetLaborPool(int LaborPoolID){ if (LaborPools->ContainsKey(__box(LaborPoolID))){ return dynamic_cast<LaborPool *>(LaborPools->Item); } else { try {
0
by: Frank | last post by:
I'm using VB in ASP.NET 2.0. I've created a dictionary with a custom key that contains 2 integers as properties. The key is in the dictionary, but when I do a ContainsKey(mykey) it always returns...
6
by: Jon Slaughter | last post by:
When I used to program in windows(back in the days of win95/98) the help system was very good. You could find out all th details of just about anything with usually decent explinations of what does...
0
by: Matthew Wieder | last post by:
I have the following requirement: A form with 2 ListViews. lvSource which contains a list of items that the user can select from and lvTarget where the selected item(s) end up. Items should...
3
by: Al Meadows | last post by:
I'm using a generic Dictionary object where it is described as: Dictionary<this, thatstuff = new Dictonary<this, that>() Where THIS is a class with several property values. This works fine...
2
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a class that inherits from Generics Dictionary The string that is used for the key is passed thru-out my pgm and sometimes it has modifiers added to the key string that are used in the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.