First of all, the reason you would have to iterate through the items (which is not a problem), is because you want to copy them.
If you'd just reference the dictionary as new internal representation, you would have multiple objects working on the same data.
This has nothing to do with you inheriting from it though - when you create a new Dictionary from another Dictionary (instead of xDictionary) - you would want the same thing.
As for the downcast - that is generally not possible, unless the type you are casting to matches the runtime-type itself or anything in the hierarchy between them.
So you won't get around it being iterated somehow, but you can pass it to the base-copy-constructor that already implemented this:
class XDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public XDictionary() { }
public XDictionary(IDictionary<TKey, TValue> dict) : base(dict) { }
}
Dictionary<string, string> d = new Dictionary<string, string>
{
{ "x", "xx" },
{ "y", "yy" },
{ "z", "zz" }
};
XDictionary<string, string> xDict = new XDictionary<string, string>(d);
Note also when you are declaring generic type-parameters for your class, you have to forward them to your base-class in order for it to make sense.
I do disagree with some of the comments below your question.
There is a guideline saying prefer composition over inheritance
, which does have it's reasons.
However, being dogmatic about it is not helpful, since with composition:
- You do have to write a lot more code to truly achieve the same base functionality.
- You have an additional object scattered over the heap.
So if your intention is not to change the Dictionary to something else - but rather extend it's functionality - inheriting from it is absolutely fine.
You can ask yourself this question for clarity:
Is my implementation supposed to be some kind of dictionary (inheritance), or to use a dictionary (composition).
There are a few things to be aware of when using inheritance, but when you are not changing the internal representation and equality/comparison mechanisms in any way, you are good for now.
If you want to modify the dictionary a bit more and not just extend it, do also consider using System.Collections.DictionaryBase
as your base class.
This abstract class will still do most of the heavy lifting for you, but provide more freedom for your implementation through abstraction.