I have a class that maintains list of objects of another class. List of objects is a public property. I would like to prevent users from adding and removing objects directly
Maybe AsReadOnly method will do the trick, to hand a read-only instance to public.
Otherwise, IEnumerable
has no Add
nor Remove
, so you can do something like:
private List _myList;
public IEnumerable MyList
{
get
{
return this._myList.ToList();
}
}
I would rather go for the IEnumerable
(+ copy) as for ReadOnlyCollection
, because: changes to your base list (which your read-only collection is created from) will immediately show up in your instance of the read-only collection. this may cause locking and straaange problems :)