Is it possible to cast a Dictionary
to a consistent intermediate generic type? So I would be able to cast
Even if you could find some way to express this, it would be the wrong thing to do - it's not true that a Dictionary
is a Dictionary
, so we definitely don't want to cast. Consider that if we could cast, we could try and put a string
in as a value, which obviously doesn't fit!
What we can do, however, is cast to the non-generic IDictionary
(which all Dictionary<,>
s implement), then use that to construct a new Dictionary
with the same values:
FieldInfo field = this.GetType().GetField(fieldName);
IDictionary dictionary = (IDictionary)field.GetValue(this);
Dictionary newDictionary =
dictionary
.Cast()
.ToDictionary(entry => (string)entry.Key,
entry => entry.Value);
(note that you can't use .Cast
here for the reasons discussed here. If you're pre-C# 4, and so don't have dynamic
, you'll have to do the enumeration manually, as Gibsnag's answer does)