Deepak Deepak - 2 months ago 17
C# Question

C# Dictionary Key/Value Ienumerable type not compatiable with Array/List

I have below piece of code and it throws error:


Cannot implicitly convert type 'System.Collections.Generic.Dictionary>' to
'System.Collections.Generic.Dictionary>'


I expect compiler to understand
IEnumerable
and
List
are compatible but it throws error. Please explain why is it like this?

Dictionary<string, List<DataRow>> sampleData = new Dictionary<string, List<DataRow>>();
Dictionary<string, IEnumerable<DataRow>> schedules = sampleData;


Thanks!

Answer

The problem is that Dictionary is not covariant, so you can't use less-derived types for its generic parameters.

Suppose your code compiled - then you could do this:

Dictionary<string, List<DataRow>> sampleData = 
    new Dictionary<string, List<DataRow>>();

Dictionary<string, IEnumerable<DataRow>> schedules = sampleData;

schedules["KeyOne"] = new DaraRow[] {null};   
// should fail since an array is not a list, and the object type requires a list.
Comments