C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?

Posted by Logan on Stack Overflow See other posts from Stack Overflow or by Logan
Published on 2010-04-28T13:04:09Z Indexed on 2010/04/28 13:13 UTC
Read the original article Hit count: 205

Filed under:
|

Hi All

I'm currently trying to write a Dump() method from LinqPad equivalent iin C# for my own amusment. I'm moving from Java to C# and this is an exercise rather than a business requirement. I've got almost everything working except for Dumping a Dictionary.

The problem is that KeyValuePair is a Value type. For most other Value types I simply call the ToString method but this is insufficient as the KeyValuePair may contain Enumerables and other objects with undesirable ToString methods. So I need to work out if it's a KeyValuePair and then cast it. In Java I could use wildcard generics for this but I don't know the equivalent in C#.

Your quest, given an object o, determine if it's a KeyValuePair and call Print on its key and value.

Print(object o) {
   ...
}

Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics