1 out of 2 rated this helpful - Rate this topic

List.AsReadOnly Method

Returns a read-only IList wrapper for the current collection.

Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)

public ReadOnlyCollection<T> AsReadOnly ()
public ReadOnlyCollection<T> AsReadOnly ()
public function AsReadOnly () : ReadOnlyCollection<T>
Not applicable.

Return Value

A ReadOnlyCollection that acts as a read-only wrapper around the current List.

To prevent any modifications to List, expose List only through this wrapper.

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

This method is an O(1) operation.

The following code example demonstrates the AsReadOnly method. A List of strings with a capacity of 4 is created, because the ultimate size of the list is known to be exactly 4. The list is populated with four strings, and the AsReadOnly method is used to get a read-only IList generic interface implementation that wraps the original list.

An element of the original list is set to "Coelophysis" using the Item property (the indexer in C#), and the contents of the read-only list are displayed again to demonstrate that it is just a wrapper for the original list.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>(4);

        Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

        dinosaurs.Add("Tyrannosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");

        Console.WriteLine();
        foreach(string s in dinosaurs)
        {
            Console.WriteLine(s);
        }

        Console.WriteLine("\nIList<string> roDinosaurs = dinosaurs.AsReadOnly()");
        IList<string> roDinosaurs = dinosaurs.AsReadOnly();

        Console.WriteLine("\nElements in the read-only IList:");
        foreach(string dinosaur in roDinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\ndinosaurs[2] = \"Coelophysis\"");
        dinosaurs[2] = "Coelophysis";

        Console.WriteLine("\nElements in the read-only IList:");
        foreach(string dinosaur in roDinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Capacity: 4

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

IList<string> roDinosaurs = dinosaurs.AsReadOnly()

Elements in the read-only IList:
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

dinosaurs[2] = "Coelophysis"

Elements in the read-only IList:
Tyrannosaurus
Amargasaurus
Coelophysis
Deinonychus
 */

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Performance issues

The AsReadOnly() method is a great generic wrapper. Suppose you've got a class named Company with a List of employee's, and you don't want the user of this class to be able to modify the list of employees, then the following construction does the trick:

public class Company
{
   private List<Employee> employees;
   ...
   public ReadOnlyCollection<Employee> Employees
   {
      get 
      {
         return employees.AsReadOnly();
      }
   }
}

However, there is a performance issue with the above construction. Although the AsReadOnly() method is rather cheap (it is O(1), as is mentioned above), it will create a new ReadOnlyCollection object every time the property Company.Employees is used. This could become problematic if used like this:

for(int i=0; i < myCompany.Employees; i++)
{
   Console.WriteLine(myCompany.Employees[i].Name);
}

If myCompany contains lots of employees, then a lot of ReadOnlyCollection objects are created, and O(1) effectively becomes O(n). So in this case we should do something like this:

public class Company
{
private List<Employee> employees;
   private ReadOnlyCollection<Employee> readonlyEmployeeCollection;
  
   ...
    
   public ReadOnlyCollection<Employee> Employees
{
get
{
         if(this.readonlyEmployeeCollection == null)
         {
            this.readonlyEmployeeCollection = this.employees.AsReadOnly(); 
         }
      
         return this.readonlyEmployeeCollection;
}
}
}