Create a read-only List for the current collection in CSharp

Description

The following code shows how to create a read-only List for the current collection.

Example


using System;/*ww w. j  a va  2  s  .  c o  m*/
using System.Collections.Generic;

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

        Console.WriteLine(myData.Capacity);

        myData.Add("A");
        myData.Add("B");
        myData.Add("C");
        myData.Add("D");

        IList<string> romyData = myData.AsReadOnly();
        
        foreach(string s in romyData){
           Console.WriteLine(s);
        }

    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary