views:

53

answers:

2

I frequently expose typed collections and lists. Often when exposing collections and lists I am not happy with the Add and Remove methods being public. In older versions of .Net I have implemented IEnumerable but this is a lot of work.

What are the better alternatives?

I have seen questions similar to this, but not specifically about the Add / Remove accessors

Thanks.

+3  A: 

Does ReadOnlyCollection(T) sove this?

EDIT

Since you want...

...to be able to add to the collection / list internally or privately

you can have a private IList<T> you'll be adding objects to, and the ReadOnlyCollection<T> will be a wrapper around this list. Since it's a wrapper, all changes to an underlying list will be reflected in this read-only collection.

Anton Gogolev
I would like to be able to add to the collection / list internally or privately. The ReadOnlyCollection appears to only let you construct with the final items.
Nanook
+1 - I was considering keeping a reference to the list used to construct the ReadOnlyCollection. I'm pleased you already confirmed it. In this case, I have nested collections which would still make it a little awkward, but still viable. I am going to persue a base collection type with protected only add and remove methods as this would be the best solution to my current issue.
Nanook
You're right, it is the correct answer. If I inherit from ReadOnlyCollection<string> and accept a List<string> as my constructor parameter, I can keep a reference in my class and also pass it to the base constructor. I can then add internal Add and Remove methods to my class. This would allow me to nest custom classes if required (instead of using string).
Nanook
A: 

Expose interface:

IEnumerable<T>
dario-g