It's not that ConcurrentBag<T>
couldn't implement ICollection<T>
; you can probably imagine that Contains
could be implemented using TryPeek
, or Remove
with TryTake
.
The issue is that treating a ConcurrentBag<T>
as an ICollection<T>
(e.g., by allowing an implicit conversion when passing a ConcurrentBag<T>
to a method that only takes ICollection<T>
) would be unwise, because most consumers of ICollection<T>
expect it to have dramatically different semantics from ConcurrentBag<T>
.
Most methods that take an ICollection<T>
as a parameter are likely to make assumptions (that are safe in a single-threaded scenario) such as "Add
followed by Contains
will always return true
", or "if Contains
returns true
, so will Remove
". However, in highly-multithreaded situations (which is where one is likely to be using ConcurrentBag<T>
in the first place), these assumptions are highly unlikely to hold. This could expose bugs in code that was written with the assumption of using ICollection<T>
in a single-threaded scenario.
If you really do need to expose ConcurrentBag<T>
as ICollection<T>
(and you know that the code you're passing it to is expecting it to work in a non-ICollection<T>
way), it should be fairly simple to write a wrapper class (that uses the adapter pattern) to simulate the methods of ICollection<T>
using the closest available methods on ConcurrentBag<T>
.
System.Collections.Concurrent
namespace.