I am wondering how I can get the key and value types of a non-generic IDictionary at runtime.
For generic IDictionary, we can use reflection to get the generic arguments, which has been answered here.
But for non-generic IDictionary, for instance, HybridDictionary, how can I get the key and value types?
Edit: I may not describe my problem properly. For non-generic IDictionary, if I have HyBridDictionary, which is declared as
HyBridDictionary dict = new HyBridDictionary();
dict.Add("foo" , 1);
dict.Add("bar", 2);
How can I find out the type of the key is string and type of the value is int?
From the msdn page:
Msdn Link
// Uses the foreach statement which hides the complexity of the enumerator.
// NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
public static void PrintKeysAndValues1( IDictionary myCol ) {
Console.WriteLine( " KEY VALUE" );
foreach ( DictionaryEntry de in myCol )
Console.WriteLine( " {0,-25} {1}", de.Key, de.Value );
Console.WriteLine();
}
// Uses the enumerator.
// NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
public static void PrintKeysAndValues2( IDictionary myCol ) {
IDictionaryEnumerator myEnumerator = myCol.GetEnumerator();
Console.WriteLine( " KEY VALUE" );
while ( myEnumerator.MoveNext() )
Console.WriteLine( " {0,-25} {1}", myEnumerator.Key, myEnumerator.Value );
Console.WriteLine();
}
// Uses the Keys, Values, Count, and Item properties.
public static void PrintKeysAndValues3( HybridDictionary myCol ) {
String[] myKeys = new String[myCol.Count];
myCol.Keys.CopyTo( myKeys, 0 );
Console.WriteLine( " INDEX KEY VALUE" );
for ( int i = 0; i < myCol.Count; i++ )
Console.WriteLine( " {0,-5} {1,-25} {2}", i, myKeys[i], myCol[myKeys[i]] );
Console.WriteLine();
}
Try this:
foreach (DictionaryEntry de in GetTheDictionary())
{
Console.WriteLine("Key type" + de.Key.GetType());
Console.WriteLine("Value type" + de.Value.GetType());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With