Search code examples
.netcollections

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 wrapping the generic IDictionary<,> in a class that implements nongenetic IDictionary however I discovered that I then have to also somehow convert generic ICollection<> to nongeneric one so I went with Mark Gravell's solution.


Solution

  • 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 */}