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:
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:
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).