0

I see System.InvalidCastException when I tried the following:

IReadOnlyDictionary<string, IReadOnlyCollection<MyType>> results = new ConcurrentDictionary<string, ConcurrentBag<MyType>>();

I do not understand the root cause for this error message:

ConcurrentBag implements IReadOnlyCollection and ConcurrentDictionary implements IReadOnlyDictionary.

Why does the casting fail?

jazb
  • 5,498
  • 6
  • 37
  • 44
Yinfang Zhuang
  • 443
  • 1
  • 5
  • 15
  • 4
    `ConcurrentBag` implements `IReadOnlyCollection`. `ConcurrentDictionary>` implements `IReadOnlyDictionary>`, but does not implement `IReadOnlyDictionary>`. – ProgrammingLlama Oct 17 '18 at 02:17
  • 2
    [Related question](https://stackoverflow.com/questions/16966961/cannot-convert-from-listderivedclass-to-listbaseclass) and [another related question](https://stackoverflow.com/questions/3720751/casting-list-of-derived-class-to-list-of-base-class). – ProgrammingLlama Oct 17 '18 at 02:18
  • 2
    Possible duplicate of [Why can't I cast a dictionary of one value type to dictionary of another value type when the value types can be cast from one another?](https://stackoverflow.com/questions/8567206/why-cant-i-cast-a-dictionary-of-one-value-type-to-dictionary-of-another-value-t) – ProgrammingLlama Oct 17 '18 at 02:25

1 Answers1

0

Instead of this:

IReadOnlyDictionary<string, IReadOnlyCollection<MyType>> results = new ConcurrentDictionary<string, ConcurrentBag<MyType>>();

You need to do this:

ConcurrentDictionary<string, IReadOnlyCollection<MyType>> results = new ConcurrentDictionary<string, IReadOnlyCollection<MyType>>();

or

ConcurrentDictionary<string, ConcurrentBag<Point>> results = new ConcurrentDictionary<string, ConcurrentBag<Point>>();

This is known as Covariance Limitation. Here is more read about it: basically, if you have a container of parent, you can put any derived class in it. But if you have a container for child, then you can't put parent in it.

In Waterfall, water falls from top to bottom.

https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/dd799517(v=vs.100)

Gauravsa
  • 6,330
  • 2
  • 21
  • 30