CSharp - ReadOnlyCollection<T> Type


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:


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

class Test/*from   ww  w  .java2 s .com*/
    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
        Console.WriteLine(t.Names.Count);       // 1

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