Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a .NET collection interface that prevents adding objects?

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 to list like this:

      MyObject.MyListProperty.Add(object); 

Instead I want them to use method that will internally do some processing and then add object to list.

I have some ideas:

  • create descendant of List<T> and override add and remove
  • return fresh copy of list through property getter (list is relatively short, not more than 30 objects)

Is there some collection interface that does not have Add and Remove?

Edit:
I'm going to go with ReadOnlyCollection<T>. Reason is that wrapped collection can be updated and changes will be immediately visible in read only object (see MSDN code examples for ReadOnlyCollection<T> and AsReadOnly()). This allows that read only list be created only once.

The problem with IEnumerable is that object can be casted back to original List<T> and then directly manipulated.

like image 875
zendar Avatar asked Feb 01 '10 11:02

zendar


People also ask

What is the base interface of all collection types in the .NET library?

The ICollection interface is the base interface for classes in the System. Collections namespace.

Is a ReadOnly collection mutable?

The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.

What is the use of ReadOnlyCollection in C#?

ReadOnly collections prevents the modification of the collection which is defined with type ReadOnly.


2 Answers

You can use ReadOnlyCollection - wrap your collection in this and return the ReadOnlyCollection to users of your class:

return new ReadOnlyCollection(innerCollection); 

Or using the AsReadOnly method of the List<T> class:

return innerCollection.AsReadOnly(); 

The IEnumerable interface will do what you need, as it only has one member GetEnumerator(), that will only let you iterate over items.

like image 105
Oded Avatar answered Sep 23 '22 20:09

Oded


Your easiest option would be to expose your list as one of the following IEnumerable, ICollection ReadOnlyCollection via a public property.

So you could create your own type of list which exposes your Items as one of the above but has an internal method for the adding e.g.

public class MyList<MyType> {     private List<MyType> items;      public MyList()     {         items = new List<MyType>();     }      public IEnumerable Items { get { return items.AsEnumerable(); } }     public Add(MyType item)     {         // do internal processing         items.Add(item);     } } 
like image 31
James Avatar answered Sep 19 '22 20:09

James