3

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!

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
SairuS
  • 149
  • 1
  • 2
  • 11

2 Answers2

2

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

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
  • Hello Rui,I dont need this, as I know that the types are equal. the issue is that I cannot compare them as one is typeof(KeyValuePair<,>).IsGenericTypeDefinition=true and item.GetType().IsGenericTypeDefinition. but type are same! – SairuS Dec 28 '12 at 15:07
2
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<,>)) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • THX it work, so my mistake was that I was trying to compare a Generic type to a non generic, Right? – SairuS Dec 28 '12 at 15:14
  • @SairuS You were trying to compare a generic type to a generic type *definition*. I know, this is really confusing: when I started with .NET reflection, it took me a few weeks to get used to this distinction. – Sergey Kalinichenko Dec 28 '12 at 15:17