sharpener
sharpener

Reputation: 1833

How to access dictionary passed as generic or even dynamic type

Let's have function Process<T>(T data). The T might be "any" (means supported) type, eg. int also as Dictionary<U,V>, where U, V are "any" types, etc. We can detect the T is dictionary using code:

var type = typeof(T); // or data.GetType();

if (   (type.IsGenericType)
    && (type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
    var dict = data as Dictionary<,>; // FIXME: Make dictionary from data

    foreach (kv in dict)
    {
        ProcessKey(kv.Key  );
        ProcessVal(kv.Value);
    }
}

Is there any way how to interpret data as dictionary or we just need separate ProcessInt(), ProcessDict<T>() where T: Dictionary<U, V>, etc?

Second level of confusion: When the function would have the form Process(dynamic data), is there any way how to access the data for the case its type is Dictionary<U, V> (please note the U, V are again "any" supported types)?

Upvotes: 0

Views: 91

Answers (1)

b2zw2a
b2zw2a

Reputation: 2693

You can use dynamics:

  if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
            {
                var dict = data as IDictionary;
                foreach (dynamic entity in dict)
                {
                    object key = entity.Key;
                    object value = entity.Value;


                    ProcessKey(key);
                    ProcessVal(value);
                }
            }

This way you can have ProcessKey and ProcessVal expecting object.

Upvotes: 1

Related Questions