ReadOnlyCollection for Read Only Collection Properties

Sometimes there are properties on Objects that are meant to provide a Read Only set of items. For example, lets say the Customer Object has a LoginHistory Property that is meant to be Read Only. Internally the values may be populated in a List<T>, but returning the List<T> would make the Collection Read/Write. One solution is to make the property an IEnumerable<T>. Here is an example:

While this approach exposes a Read Only Collection, there are a couple of problems with the IEnumberable<T> interface. On the other side of the code, it is now difficult to know how many items are there in this collection, or if there is any item at all (Except with the help of Linq's Any() and Count() Extension Methods)! Having a Count Property would be helpful. Besides, the Collection is not really Read Only in this case. You could Cast this LoginHistory Property to a List<T> and Add Items to it:

A better approach would be to return the generic ReadOnlyCollection<T> instead if IEnumerable<T>. This class is in the System.Collections.ObjectModel Namespace, and List<T> has a Method called AsReadOnly() that returns a ReadOnlyCollection<T> Object. The LoginHistory Property would be implemented as follows:

There is a Count Property now, and Customer.LoginHistory is truly Read Only!

Posted on January 6, 2010 10:04 by Haider

Comments

Don't Post SPAM

If you are posting a commment just to get a link, don't waste your time!

I have a sophisticated comment moderation system in place, and your comment will not be posted.

Add comment




biuquote
  • Comment
  • Preview
Loading