views:

1064

answers:

1

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.

+8  A: 

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 */}
Marc Gravell