ReadOnlyCollection<T> Class
Namespace: System.Collections.ObjectModel
Assembly: System.Runtime.dll
Assembly: System.Runtime.dll
Summary
Represents a collection that cannot be written to. The methods that add, remove, or change the collection will throw an NotSupportedException.
This class provides a read-only wrapper around an existing collection. It is useful when you want to expose a collection to the outside world but prevent any modifications to its contents.
Constructors
public ReadOnlyCollection(IList<T> list)
Initializes a new instance of the
ReadOnlyCollection<T>
class that wraps the specified list.
Methods
public void Add(T item)
Always throws a NotSupportedException.
public void Clear()
Always throws a NotSupportedException.
public int IndexOf(T item)
Returns the zero-based index of the specified object in the ReadOnlyCollection<T>.
public void Insert(int index, T item)
Always throws a NotSupportedException.
public bool Remove(T item)
Always throws a NotSupportedException.
public void RemoveAt(int index)
Always throws a NotSupportedException.
Properties
public T this[int index] { get; }
Gets the element at the specified index.
public int Count { get; }
Gets the number of elements contained in the ReadOnlyCollection<T>.
Interfaces
IList<T>
Interface
ICollection<T>
Interface
IEnumerable<out T>
Interface
ICollection
Interface
IEnumerable
Interface
IList
Interface
Example Usage
Here's how you can use the ReadOnlyCollection<T>
class:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Example
{
public static void Main()
{
List<string> mutableList = new List<string> { "apple", "banana", "cherry" };
// Create a read-only view of the mutable list
ReadOnlyCollection<string> readOnlyView = new ReadOnlyCollection<string>(mutableList);
Console.WriteLine("Read-only view:");
foreach (var fruit in readOnlyView)
{
Console.WriteLine($"- {fruit}");
}
Console.WriteLine($"Count: {readOnlyView.Count}");
// Trying to modify will throw an exception
try
{
readOnlyView.Add("date");
}
catch (NotSupportedException ex)
{
Console.WriteLine($"\nCaught expected exception: {ex.Message}");
}
// Modifying the original list is still possible
mutableList.Add("date");
Console.WriteLine($"\nOriginal list modified. New count of read-only view: {readOnlyView.Count}");
}
}