CSharp - ReadOnlyCollection<T> Type

Introduction

ReadOnlyCollection<T> type provides a read-only view of a collection.

A read-only collection accepts the input collection in its constructor.

Subsequent changes to the input collection are visible through the read-only wrapper.

The following code use read only collection to control element access.

Only members within the Test class can alter the list of names:

Demo

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

class Test/*from  ww  w  .j av  a 2s . c o  m*/
{
    List<string> names;
    public ReadOnlyCollection<string> Names { get; private set; }

    public Test()
    {
        names = new List<string>();
        Names = new ReadOnlyCollection<string>(names);
    }

    public void AddInternally() { names.Add("test"); }
}

class MainClass
{
    public static void Main(string[] args)
    {
        Test t = new Test();

        Console.WriteLine(t.Names.Count);       // 0
        t.AddInternally();
        Console.WriteLine(t.Names.Count);       // 1

        // t.Names.Add ("test");                    // Compiler error
        //  ((IList<string>) t.Names).Add ("test");  // NotSupportedException
    }
}

Result