C# cast Dictionary<string, AnyType> to Dictionary<string, Object> (Involving Reflection)
Following AakashM's answer, the Cast doesn't seem to play ball. You can get around it by using a little helper method though:
IDictionary dictionary = (IDictionary)field.GetValue(this);
Dictionary<string, object> newDictionary = CastDict(dictionary)
.ToDictionary(entry => (string)entry.Key,
entry => entry.Value);
private IEnumerable<DictionaryEntry> CastDict(IDictionary dictionary)
{
foreach (DictionaryEntry entry in dictionary)
{
yield return entry;
}
}
The duck typing in foreach is handy in this instance.
Is this helping you ?
Dictionary<a, b> output =
input.ToDictionary(item => item.Key, item => (SomeType)item.Value);
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<string, bool>
is a Dictionary<string, object>
, 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<string, object>
with the same values:
FieldInfo field = this.GetType().GetField(fieldName);
IDictionary dictionary = (IDictionary)field.GetValue(this);
Dictionary<string, object> newDictionary =
dictionary
.Cast<dynamic>()
.ToDictionary(entry => (string)entry.Key,
entry => entry.Value);
(note that you can't use .Cast<DictionaryEntry>
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)