ReadOnlyCollection<T>
ReadOnlyCollection<T> is a wrapper, or proxy, that provides a read-only view of a
collection. This is useful in allowing a class to publicly expose read-only access to a
collection that the class can still update internally.
A read-only collection accepts the input collection in its constructor, to which it
maintains a permanent reference. It doesn’t take a static copy of the input collection,
so subsequent changes to the input collection are visible through the read-only
wrapper.
To illustrate, suppose your class wants to provide read-only public access to a list
of strings called Names:
public class Test
{
public List<string> Names { get; private set; }
}
This only does half the job. Although other types cannot reassign the Names property,
they can still call Add, Remove, or Clear on the list. The ReadOnlyCollection<T> class
resolves this:
public class Test
{
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"); }
}
Now, only members within the Test class can alter the list of names:
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
No comments:
Post a Comment