Question

I have a issue where I want to identify if a object is of type KeyValuePair<,>

when I compare in if:

else if (item.GetType() == typeof(KeyValuePair<,>))
{
    var key = item.GetType().GetProperty("Key");
    var value = item.GetType().GetProperty("Value");
    var keyObj = key.GetValue(item, null);
    var valueObj = value.GetValue(item, null);
    ...
}

this is false as IsGenericTypeDefinition is different for them.

Can someone explain me why this is happening and how to solve the this issue in correct way (I mean not comparing Names or other trivial fields.)

THX in advance!

Was it helpful?

Solution

item.GetType() == typeof(KeyValuePair<,>)

The above will never work: it is impossible to make an object of type KeyValuePair<,>.

The reason is that typeof(KeyValuePair<,>) does not represent a type. Rather, it is a generic type definition - a System.Type object used to examine structures of other generic types, but not themselves representing a valid .NET type.

If an item is, say, a KeyValuePair<string,int>, then item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)

Here is how you can modify your code:

...
else if (item.IsGenericType() && item.GetGenericTypeDefintion() == typeof(KeyValuePair<,>)) {
    ...
}

OTHER TIPS

Found this piece of code, give it a try:

public bool IsKeyValuePair(object o) 
{
    Type type = o.GetType();

    if (type.IsGenericType)
    {
        return type.GetGenericTypeDefinition() != null ? type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) : false;
    }

    return false;
}

Source:

http://social.msdn.microsoft.com/Forums/hu-HU/csharpgeneral/thread/9ad76a19-ed9c-4a02-be6b-95870af0e10b

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top