Type safety for Dictionary keys?

I am planning to use multiple name-indexed dictionaries in a project. My first choice was to use a string key, which is just the Name property of my Value elements.

However, this makes the dictionary keys identical even though they are accessing different types:

private Dictionary<string, Foo> myFoos; private Dictionary<string, Bar> myBars; myFoos[bar.Name]; // shouldn't be able to do this!

I would like the keys to be type-incompatible with each other to make them impossible to confuse with each other:

private Dictionary<FooName, Foo> myFoos; private Dictionary<BarName, Bar> myBars;

Since creating a *Name class for each Value type is overkill, I created a Name<T> class:

public struct Name<T> { public string Name; // for convenience, could be explicit instead static implicit operator string(Name<T> name) { return name.Name; } }

which would give me

private Dictionary<Name<Foo>, Foo> myFoos; private Dictionary<Name<Bar>, Bar> myBars;

and then I could store Name<Foo> instances instead of strings.

This seems a bit unwieldy, but it's the best I've come up with so far - any suggestions on how to do it better?
Is this misguided, or awesome?


The first question is:

I would like the keys to be type-incompatible with each other to make them impossible to confuse with each other:

Why? Is there actually a chance of confusion? This isn’t obvious. Mind you, I’m not saying that your method is bad; in fact, in fact, there are probably real benefits from this. But consider array indexers:

int a[];
float b[];

The types of the arrays are incompatible yet both use integer indices. And yes, this can actually lead to problems when the indices are confused – probably the same kinds of problems that you are facing with your keys.

So this case is exactly analogous to yours. Perhaps using the same key types for different containers isn’t that bad after all (even though in theory you are right and there’s the risk of confusion).

That will work, except that you need to override Equals and GetHashCode to make the names compare by value.

Category:c# Time:2011-01-07 Views:0

Related post

  • What must be done to use the value of a reference type as a dictionary key? 2010-05-21

    Suppose I have a class T that I want to use as a key in a Dictionary<T,U> collection. What must I implement in T so that these keys are based on values of T rather than T references? I'm hoping it's just GetHashCode(). --------------Solutions--

  • xmlrpclib: dictionary key must be string type error 2011-08-09

    I would like some advice. I have encountered the following error in Python 2.6: Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> s.Search(query) File "/usr/lib/python2.6/xmlrpclib.py", line 1199, in __call__ ret

  • Polymorphic (pure abstract) map key sacrifices type safety? 2011-10-28

    Some context: (Feel free to skip ahead) I have a module that processes complex data, but only has to know some semantics of it. The data can be considered a packet: The module should only reason about the opaque payload-string, but it will eventually

  • Thread safety with Dictionary in .Net 2011-08-30

    I have this function: static Dictionary<int, int> KeyValueDictionary = new Dictionary<int, int>(); static void IncreaseValue(int keyId, int adjustment) { if (!KeyValueDictionary.ContainsKey(keyId)) { KeyValueDictionary.Add(keyId, 0); } Ke

  • Type safety: Unchecked cast 2008-11-04

    In my spring application context file, I have something like: <util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String"> <entry key="some_key" value="some value" /> <entry key="some_

  • Selecting a good dictionary key 2009-03-20

    I have an object that I want to use to look up other objects. I will be using a Dictionary<TKey, TValue>(). The key object has two strings that uniquely identify it, say KeyObj.Str1 and KeyObj.Str2. What do you recommend that I use as the key f

  • Is there any character limitation in Dictionary Keys? 2009-05-17

    In .NET can I use any string as a dictionary key? This is part of a templating engine and I'm planning allow users to add their custom headers and values. Headers will be something like "Value of X" or "Summary of Analyse & XYZ Reports", I'm worr

  • What is type-safety? 2009-05-29

    I had a brainbench exam recently, got high mark, but there were a couple of questions which were hard for me. Maybe it's because english is not my native language... One of the questions is: Which one of the following describes type-safety? A program

  • Java 6 Map.get() Type Safety Unexpected Behavior(?) 2009-06-25

    Possible Duplicate: What are the reasons why Map.get(Object key) is not (fully) generic According to the javadocs (http://java.sun.com/javase/6/docs/api/java/util/Map.html) for the Map interface, the definition of get is V get(Object key) Returns the

  • get dictionary key by value 2010-03-14

    Possible Duplicate: Getting key of value of a generic Dictionary? How do I get a Dictionary key by value in C#? Dictionary<string, string> types = new Dictionary<string, string>() { {"1", "one"}, {"2", "two"}, {"3", "three"} }; I want som

  • python: identifying duplicate values across disparate dictionary keys 2010-05-19

    here is an example of the dict ActivePython (ActiveState Software Inc.) based on Python 3.1.2 (r312:79147, Mar 22 2010, 12:20:29) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >

  • How to solve this Java type safety warning? 2010-05-28

    Map session = ActionContext.getContext().getSession(); session.put("user", user); This code generates a warning: Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map should be parameterized. Map<S

  • UIView as dictionary key? 2010-06-07

    I want to have a NSDictionary that maps from UIViews to something else. However, since UIViews do not implement the NSCopying protocol, I can't use them directly as dictionary keys. --------------Solutions------------- You can use an NSValue holding

  • Creating a comparable Dictionary Key 2010-08-30

    I want to use a Dictionary(Of Key, Value), and the Key is not a base type, but a class like: Public Class MyKey Sub New(ByVal packet As String, ByVal sent As Boolean) Me.packet = packet.ToUpper.Trim Me.sent = sent End Sub Private packet As String Pri

  • Python dictionary keys besides strings and integers? 2010-12-03

    Anyone have some neat examples of dictionaries with some interesting keys (besides the canonical string or integer), and how you used these in your program? I understand all we need for a key is something hashable, meaning it must be immutable and co

  • Possible to create an implicit cast for an anonymous type to a dictionary? 2011-01-08

    I wrote a method like this: using AttrDict = System.Collections.Generic.Dictionary<string, object>; using IAttrDict = System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>; static string Htm

  • Does Dictionary.Keys.List()[i] correspond to Dictionary.Values.ToList()[i]? 2011-02-10

    I have a Dictionary data type. My question is, is Dictionary.Keys.ToList()[i] always correspond to Dictionary.Values.ToList()[i] ? That is, will the following test always passes public void DictionaryTest(int i, Dictionary<U,T> dict) { var key

  • Best approach to multi-part int dictionary key? 2011-02-11

    Say my dictionary needs to be keyed by a combination of ItemId and RegionId, both int. And say the type of the value side is "Data". I could do this a couple of ways: Way 1: multi-level dictionary, like this: Dictionary<int, Dictionary<int, Dat

  • Optimizing memory requirements for Dictionary keys 2011-02-26

    Save that I have a (large) collection of instances of Dictionary. The key value in that dictionary is always one of say 10 known strings. If the collection contains 1000000 entries, will the that string key value occupy memory for each instance and k

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 2.782 (s). 13 q(s)