2

I'm trying to create interface with method

void Import(int id, IDictionary<int, IDictionary<int, string>> items);

then call this method like

Dictionary<int, Dictionary<int, string>> items = viewModel.Items
  .GroupBy(t => t.Number)
  .ToDictionary(t => t.Key, t => t.ToDictionary(x => x.LanguageId, x => x.Translation));


Import(id, items);

I expected that it should works but got an error

cannot convert from 'System.Collections.Generic.Dictionary<int, System.Collections.Generic.Dictionary<int, string>>' to 'System.Collections.Generic.IDictionary<int, System.Collections.Generic.IDictionary<int, string>>'  

Why I can't use interface IDictionary here? Should I cast manually?

Pr.Dumbledor
  • 636
  • 1
  • 11
  • 29
  • The error message you get is to be expected. It's for the same reason that it's a compilation error to assign a `List` to a `List`, even though you can assign a `Dog` to an `Animal`. – DodgyCodeException Mar 16 '18 at 16:41
  • ToDictionary extension from System.Linq returns a Dictionary not the interface, i suppose the error is when he calls import – animalito maquina Mar 16 '18 at 16:45
  • 1
    @animalitomaquina - This has to do with covariance. Example: `List` is not assignable to an instance of type `List` even if `Monkey` implements interface `IMonkey`. – Igor Mar 16 '18 at 16:45
  • 1
    More explanation: https://stackoverflow.com/questions/1817300/convert-listderivedclass-to-listbaseclass – DodgyCodeException Mar 16 '18 at 16:47

1 Answers1

5

Change your assigning type.

Dictionary<int, IDictionary<int, string>> items = viewModel.Items
  .GroupBy(t => t.Number)
  .ToDictionary(t => t.Key, t => (IDictionary<int, string>) t.ToDictionary(x => x.LanguageId, x => x.Translation));
Igor
  • 60,821
  • 10
  • 100
  • 175