Jaine Jaine - 3 years ago 170
C# Question

Unable to recognize Dictionary object through Reflection

I am playing with Reflections and stopped with the next problem.

I can't recognize that the object is of the Dictionary<,> Type.

I receive PropertyInfo from Top object, and this property is of Dictionary<,> class for sure.

Then I do the next:

if (pi.PropertyType.IsGenericType && pi.PropertyType == typeof(IDictionary<,>))


or

if (pi.PropertyType.IsGenericType && pi.PropertyType == typeof(KeyValuePair<,>))


and in both cases the second comparision's without success.

Does anyone know another way to 100% recognize a Dictionary Type object?

Answer Source

The type in the PropertyType is a closed generic type (Dictionary<string, int> for example) where the type parameters are known. You want to check if the type is any Dictionary<,> (called an open generic type).

You should do:

pi.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download