5

I was wondering, assume I have a ConcurrentBag encapsulated in an object like this

class Package
{
   private ConcurrentBag<string> myList;
   public string title {get; private set;}
   public string description {get; private set;}

   public Package(string title,string description)
   {
       myList = new ConcurrentBag<string>();
       this.title = title;
       this.description = description;
   }


   public override string ToString()
   {
       return title + " " + description;
   }
}

How would I return a read-only version of my ConcurrentBag?

Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
  • 1
    Do you want a read-only interface like [IReadOnlyCollection](http://msdn.microsoft.com/en-us/library/hh881542.aspx) or do you want it throw exceptions when `Add` is called, like [ReadOnlyCollection](http://msdn.microsoft.com/en-us/library/ms132474.aspx) does? – Patrick Quirk Jan 15 '13 at 22:18
  • I only want to return Read-Only collection of my ConcurrentBag, so I would guess IReadOnlyCollection. – Scott Anderson Jan 15 '13 at 22:19

2 Answers2

0

why don't you return a clone? I know it's not ideal but otherwise you will have to make your own custom ConcurentBagReadOnly.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
alexb
  • 971
  • 6
  • 12
-2

Since you're looking for functionality close to IReadOnlyCollection which only offers a Count property, I would expose it as IEnumerable<string> and rely on LINQ extensions to query it.

Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
  • Good point, according to [this question](http://stackoverflow.com/questions/9995266/how-to-create-a-thread-safe-generic-list) they are not. You might be able to go the same route offered in an answer there and expose the functionality that you need to by wrapping calls to LINQ with locks. – Patrick Quirk Jan 15 '13 at 22:35
  • Exposing original collection will give possibility to cast it to original type and modify its content. – Evgeny Gorbovoy Jun 13 '20 at 19:58