1

I have an object that is of type KeyValuePair<T1,T2> , but the actual types of T1,T2 are only known at run time. I would like to extract Key and Value of that object but I do not know how. Could you please help? (The idea is as below but it does not work)

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) {
     KeyValuePair<object, object> kvp = (KeyValuePair<object, object>)obj;
     Console.WriteLine("[{0},{1}]", kvp.Key, kvp.Value);
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Nghia Le
  • 535
  • 2
  • 6
  • 16
  • 2
    http://stackoverflow.com/questions/11576886/how-to-convert-object-to-dictionarytkey-tvalue-in-c ? – Vrashabh Irde Nov 26 '14 at 05:55
  • Thank you! I already thought of using reflection but I referred a possible way of casting/converting. I was a little worry about reflection performance (I have to convert a lot of these objects) but it seems the only way. – Nghia Le Nov 26 '14 at 06:18
  • 1
    When the type is literally known by _none_ of the code at compile time, you're pretty much stuck with reflection or `dynamic`. E.g. "KeyValuePair = new KeyValuePair(((dynamic)obj).Key, ((dynamic)obj).Value)`. That said, these scenarios are unusual. It's likely there's a better approach in your particular scenario, but without more context it's not really possible to say in any specific way what that better approach would be. – Peter Duniho Nov 26 '14 at 06:53

0 Answers0