When I assign a Dictionary<int, HashSet<int>>
to a IDictionary<int, IEnumerable<int>>
, I get the following error:
Compilation error (line 27, col 9): Cannot implicitly convert type 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'. An explicit conversion exists (are you missing a cast?)
The error is quite clear. A cast is missing. Why do I need a cast here? Dictionary<T,U>
implements IDictionary<T,U>
and HashSet<T>
implements IEnumerable<T>
.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class A
{
public IDictionary<int, IEnumerable<int>> D { get; set; }
public IEnumerable<int> H { get; set; }
}
public static void Main()
{
var hashSet = new HashSet<int>{1,2,1};
var a = new A { H = hashSet };
PrintCollection(a.H);
var d = new Dictionary<int, HashSet<int>>{{ 3, hashSet }};
a.D = d; // error here
PrintCollection(a.D.First().Value);
}
public static void PrintCollection(IEnumerable<int> collections)
{
foreach (var item in collections)
Console.WriteLine(item);
}
}