I have:
IDictionary<string, IDictionary<string, IList<long>>> OldDic1;
(just for illustration purposes, it is instantiated and has values – somewhere else)
Why can I do this: ?
Dictionary<string, IDictionary<string, IList<long>>> dic1 =
OldDic1 as Dictionary<string, IDictionary<string, IList<long>>>;
Basically dic1 after executing this line has all the values from OldDic1; works.
However when I do this:
Dictionary<string, Dictionary<string, List<long>>> dic1 =
OldDic1 as Dictionary<string, Dictionary<string, List<long>>>;
I get null, it is the same as casting except it doesn’t crash and instead it returns null. So the question is why I can’t cast it from the interfaces to types? is there solution, other then changing how it is stored in the first place?
You can only re-cast the outermost interface/class name, not the generic parameters. The reason your second cast doesn’t work is the same reason you can’t cast from one array type to another even if you can cast the “contained” objects. Here’s why:
The same thing would happen in your second case. You could add some kind of
IDictionarytoOldDic1which is not actually aDictionary, and thendic1would blow up. It would have a non-Dictionaryvalue. Ruh roh!So, when you have containers you can change from
IList<X>toList<X>and back as long asXis identical for each.