.NET Tip: Creating a Read-Only List

Have you ever had the need to expose a read-only list? I'm not just talking about a List<T> property that could not be set directly, but one that could not have any elements added, removed, or modified? There is a simple way to do this by using the AsReadOnly() method of a List<T>. Here is an example class that uses a List<string> to store the names of the authors of Design Patterns.

public class Patterns
{
   List<string><string> _GangOfFourAuthors =
      new List<string> { "Gamma", "Helm", "Johnson", "Vlissides" };

   public IList<string><string> GangOfFourAuthors
   {
      get { return _GangOfFourAuthors.AsReadOnly(); }
   }

   public void AddMe()
   {
      _GangOfFourAuthors.Add("Miller");
   }
}

A List<string> is created and initialized with the names of the authors. The GangOfFourAuthors property returns a read-only IList<string>. Look at a quick example of using the class and property to print the names of the authors to the Output window.

Patterns p = new Patterns();
IList<string> Authors = p.GangOfFourAuthors;

foreach (string a in Authors)
    Debug.WriteLine(a);

Output:
Gamma
Helm
Johnson
Vlissides

This code creates a new Patterns object, retrieves the list of authors, and then prints them to the Output window. You can see that the output matches the initialization of the List<string> in the Patterns class. At this point, elements of Authors cannot be added, removed, or modified. The following code would throw an error:

Authors.Add("Miller"); 

Authors cannot be changed in any way without causing an error. The original list, however, can be modified and those changes will be reflected in the read-only version of the list. If you look at the AddMe() method in the Patterns class above, you will see that it adds an element to the internal List<string> of authors. Here is code that calls that method and then outputs the list of authors.

Patterns p = new Patterns();
IList<string> Authors = p.GangOfFourAuthors;

p.AddMe();

foreach (string a in Authors)
   Debug.WriteLine(a);

Output:
Gamma
Helm
Johnson
Vlissides
Miller

The AsReadOnly() method provides an easy way to restrict access to your classes' data. The method is available for List<T> as well as arrays.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds