kaalus
kaalus

Reputation: 4574

How to get value from a KeyValuePair<> with unknown type

I have an object that is a KeyValuePair<> whose types I do not know. I need to get the Value of this KeyValuePair as object.

object kvpair = ... ;         // This is a KeyValuePair<K, V> with unknown K and V.
object value = kvpair.Value;  // I want to get the value of the kvpair

I understand this will involve using reflection.

Upvotes: 0

Views: 1069

Answers (1)

Damian
Damian

Reputation: 1374

Please see the following topic. You will find more than you need there: C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?

LE:

KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("key", "value");
Type aux = kvp.GetType();
object kvpValue = aux.GetProperty("Value").GetValue(kvp, null);
Console.WriteLine(kvpValue);

Upvotes: 3

Related Questions