Simple Example of the ReadOnlyCollection in C#

The following example demonstrates the simple example of the ReadOnlyCollection class. In the Example we create the a List object with the several cities name and then we wrap this list into a ReadOnlyCollection.

    List<string> citiesList = new List<string>();
 
	citiesList.Add("NewDelhi");
    citiesList.Add("Londan");
    citiesList.Add("NewYork");
    citiesList.Add("Tokyo");
 
     ReadOnlyCollection<string> readOnlycities =
        new ReadOnlyCollection<string>(citiesList);

Get the Count of the items in the ReadOnlyCollection.

With the help of the Count property we can getthe number of elements contained in the ReadOnlyCollection instance just like as:

  Console.WriteLine("\nCount: {0}", readOnlycities.Count);

ReadOnlyCollection is just a wrapper for the original List.
the code example shows that the ReadOnlyCollection is just a wrapper for the original List by adding a new item to the List and displaying the contents of the ReadOnlyCollection.

cities.Insert(3, "Paris");
foreach (string city in readOnlycities)
{
  Console.WriteLine(city);
}

The result will be:

NewDelhi
Londan
NewYork
Paris
Tokyo

The object of the ReadOnlyCollection generic class will be always read-only. and if changes are made to the underlying collection, the read-only collection object reflects those changes.