2

I can do this

IReadOnlySet<string> set = new HashSet<string>();

but I can't do this:

Dictionary<string, IReadOnlySet<string>> dictSet = new Dictionary<string, HashSet<string>>();

and I'm wondering why this is so?

Can this cast be done somehow or is it a case of having to create a whole new Dictionary? It seems rather inefficient to have to do this:

var dictSetPrep = new Dictionary<string, HashSet<string>>();
// Here we would add items to dictSetPrep

var dictSet = new Dictionary<string, IReadOnlySet<string>>();
foreach (var kvp in dictSetPrep) {
    dictSet.Add(kvp.Key, kvp.Value);
}
Charlieface
  • 52,284
  • 6
  • 19
  • 43
Elliveny
  • 2,159
  • 1
  • 20
  • 28
  • 2
    In short - because C# does not support variance for classes. – Guru Stron Sep 28 '22 at 11:40
  • See [this](https://stackoverflow.com/a/246101/2501279) – Guru Stron Sep 28 '22 at 11:41
  • There's no need to create a new dictionary. Your `Dictionary>` will still accept `HashSet` values, it just can't be assigned a dictionary that, in its contract, will *only* accept `HashSet` values and not any `IReadOnlySet`, as the declaration is promising. – Jeroen Mostert Sep 28 '22 at 11:42
  • Thanks for the pointers here everyone and apologies for the duplicate question thing. As soon as variance and covariance were mentioned I remembered falling over something similar in the past. I guess I can't escape the expectation that this should just work - it instinctively feels like something you should be able to do, to me at least! – Elliveny Sep 28 '22 at 12:48

0 Answers0