get key and value list from unknown typed dictionary without using dynamic

I am trying to convert a dictionary into key value pairs so I can do some special parsing on it and store it in string format. I am using Unity so I cannot use the dynamic keyword. Here is my setup

I have some class which I am iterating across its properties and manipulating their value and putting them in a new dictionary. The problem is I don't know how to get the keys and values out of a dictionary for which I do not know the types without using the dynamic trick. Any thoughts? I will need to do the same with lists.

    Type t = GetType();
    Dictionary<string, object> output = new Dictionary<string, object>();
    foreach(PropertyInfo info in t.GetProperties())
    {
        object o = info.GetValue(this, null);
        if(info.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            foreach(object key in o) //not valid
            {
                object val = DoSomething(o[key]);//not valid
                output[key] = val;
            }
        }
        else if(info.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
        {

        }
    }
    return output;
Jon Skeet
people
quotationmark

Dictionary<TKey, TValue> also implements the non-generic IDictionary interface, so you can use that:

IDictionary d = (IDictionary) o;
foreach(DictionaryEntry entry in d)
{
    output[(string) entry.Key] = entry.Value;
}

Note that this will obviously fail if the key type isn't string... although you could call ToString instead of casting.

You can easily check for any IDictionary implementation, in fact - not just Dictionary<,> - without even having the nasty reflection check:

IDictionary dictionary = info.GetValue(this, null) as IDictionary;
if (dictionary != null)
{
    foreach (DictionaryEntry entry in dictionary)
    {
        output[(string) entry.Key] = entry.Value;
    }
}

people

See more on this question at Stackoverflow