Reputation: 43
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?
Upvotes: 4
Views: 1873
Reputation: 6259
Non-generic dictionaries don't necessarily have a type of key or value in the same way as a generic dictionary would. They can take any type as a key, and any type as a value.
Consider this:
var dict = new System.Collections.Specialized.HybridDictionary();
dict.Add(1, "thing");
dict.Add("thing", 3);
It has keys of multiple types, and values of multiple types. So, what type would you say the key is, then?
You can find out the type of each individual key and individual value, but there's no guarantee that it's all the same type.
Upvotes: 1
Reputation: 1636
Try this:
foreach (DictionaryEntry de in GetTheDictionary())
{
Console.WriteLine("Key type" + de.Key.GetType());
Console.WriteLine("Value type" + de.Value.GetType());
}
Upvotes: 2
Reputation: 800
From the msdn page:
// 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();
}
Upvotes: 2