Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key and value types of non-generic IDictionary at runtime

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?

like image 335
Yang Zou Avatar asked Oct 22 '25 06:10

Yang Zou


2 Answers

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();
   }
like image 133
duyker Avatar answered Oct 23 '25 19:10

duyker


Try this:

foreach (DictionaryEntry de in GetTheDictionary())
{
    Console.WriteLine("Key type" + de.Key.GetType());
    Console.WriteLine("Value type" + de.Value.GetType());
}
like image 21
Kirin Yao Avatar answered Oct 23 '25 18:10

Kirin Yao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!