Anders,
Why not just derive from Dictionary<TKey, TValue> and then add a new
method? Something like this:
public TValue GetValue(TKey key)
{
// Check for existence here.
if (this.ContainsKey(key))
{
// Return the value.
return this[key];
}
// The key does not exist, return the default.
return default(T);
}
The problem with this is that it is valid in a Dictionary to have null
as a value corresponding to a key. The dictionary is more correct in that
sense.
You are right, using the if statement might incur an extra overhead, but
I wouldn't think that it is that much. Have you tried to use the check
against ContainsKey, and then measure the performance to see if you are
truly impacted by it?
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Anders Borum" <an****@sphereworks.dk> wrote in message
news:%2******************@TK2MSFTNGP09.phx.gbl...
Hello!
I am using Hashtables to cache data in services and am looking at generics
for typed access (I control the key/value types). However, I was surprised
to see that the Dictionary throws a KeyNotFoundException if you try to
reference missing keys, which is a change from the Hashtable.
So what?
Well, the idea of a cache is to ensure high performance (low latency)
access to your data, and wrapping "if" statements around each "get" call
sounds expensive. I like the typed access to my cache, but dislike the
overhead .. (not sure whether the Hashtable implementation calls
.ContainsKey internally before returning null / value).
// Typed version (dictionary) - the ContainsKey method is another
// member I've implemented
public CmsObjectNode GetItem(Guid key)
{
return (this.ContainsKey(key)) ? this.cmsObjectNodeCache[key] : null;
}
// Untyped version (hashtable)
public CmsObjectNode GetItem(Guid key)
{
return this.cmsObjectNodeCache[key] as CmsObjectNode;
}
Your comments?
Thanks in advance!
--
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)