C# cast Dictionary to Dictionary (Involving Reflection)

ccastingreflection

Is it possible to cast a Dictionary<string, Anything> to a consistent intermediate generic type? So I would be able to cast <string, string>, <string, bool>, <string, int>, <string, anything> all to the same type of dictionary?

I am working on a project that is using heavy reflection and I need to be able to process DIctionary types as such:

FieldInfo field = this.GetType().GetField(fieldName);
Dictionary<string, Object> dict = (Dictionary<string, Object>)field.GetValue(this);

The above code is what I currently have and the program always fails at the cast from field.GetValue to the generic Dictionary<string, Object>.

Is there a way to do this? Or should I just figure out a different way to process these Dictionaries?

Any help would be greatly appreciated.

Best Answer

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.

Related Topic