Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert generic dictionary to non-generic without enumerating?

I want to convert an instance of generic IDictionary to non generic IDictionary. Can I do it without creating new instance of IDictionary? Is any framework support for this task?

I tried wrap generic IDictionary in class that implements nongenetic IDictionary however I discovered that I have to also somehow convert generic ICollection to nongeneric one so I go with Mark Gravell solution.

like image 1000
Jakub Šturc Avatar asked Sep 29 '08 08:09

Jakub Šturc


1 Answers

It all depends on the concrete implementation you are using.

For example, Dictionary<TKey,TValue> implements both the generic IDictionary<TKey,TValue> and the non-generic IDictionary - so if you have a Dictionary<TKey,TValue> you can use it as either without issue:

        Dictionary<int, string> lookup = new Dictionary<int,string>();
        IDictionary<int,string> typed = lookup;
        IDictionary untyped = lookup;

However, this doesn't necessarily apply for all IDictionary<TKey,TValue> imlpementations, since it is not true that IDictionary<TKey,TValue> : IDictionary. If you are deep in the bowels of some generic code, you could test the current dictionary:

        IDictionary<int,string> typed  = ...
        IDictionary untyped = typed as IDictionary;
        if(untyped == null) {/* create by enumeration */}
like image 122
Marc Gravell Avatar answered Oct 24 '22 04:10

Marc Gravell