Exercise: Unmodifiable collections

In the exercise Generic Catalog add a method GetAll() which returns all the elements in the catalog.

Problem

This method is dangerous since it returns a reference to a private data structure inside the Catalog class. With this reference an evil programmer can do anything he likes to the private data structure.

Solution

Return an unmodifiable version of the private datastructure - or a copy of the private data structure.

In this exercise you will try different ways to make unmodifiable or copied collecions.

ReadOnlyCollection

Make another method to the Catalog class

This method must return an unmodifiable version of the elements in the catalog.

Hint: Use the class ReadOnlyCollection

ReadOnly ICollection

Make yet another method to the Catalog class

This method must return a read-only version of the collection. If the client calls a modyfing method like Add(...) the client gets an exception

Hint: Use the method list.AsReadOnly()

Unit testing: Yes

Copied collection

Make yet another method to the Catalog class

This methodwhich return a copy of the elements in the catalog.

Hint: The copy constructor of the class Collection<T>(IList<T> list) is a very thin wrapper of the list. Not suitable for this job.

Hint2: Do you own hand copying: Make a Collection<T> object, loop through all elements in the original collection and add the elements to the new Collection object.

IEnumerable<T> collection

Make yet another method

Since IEnumerable<T> is a super-type of ICollection<T>, and hence of IList<T>, ISet<T>, etc. you can just return the collection as it is.

The evil programmer still have a chance ...

The evil programmer might do some nasty typecasting to get the original type back.

Now the evil programmer can do much too much to the coll object.