C# > Advanced C# > Collections and Generics > ReadOnlyCollection<T>
Using ReadOnlyCollection to Protect Internal Data
This code snippet demonstrates how to use `ReadOnlyCollection
Scenario
Imagine a class that manages a list of employees. You want to provide access to this list to other parts of your application, but you don't want them to be able to directly add, remove, or modify the employees. Using `ReadOnlyCollection
Code Example
This code defines an `EmployeeManager` class that holds a list of employee names. The `Employees` property is a `ReadOnlyCollection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class EmployeeManager
{
private List<string> employeeList = new List<string>();
public ReadOnlyCollection<string> Employees { get; private set; }
public EmployeeManager()
{
employeeList.Add("Alice Smith");
employeeList.Add("Bob Johnson");
Employees = new ReadOnlyCollection<string>(employeeList);
}
public void AddEmployee(string name)
{
employeeList.Add(name);
//Recreate the ReadOnlyCollection if underlying list is modified
Employees = new ReadOnlyCollection<string>(employeeList);
}
public void RemoveEmployee(string name)
{
employeeList.Remove(name);
//Recreate the ReadOnlyCollection if underlying list is modified
Employees = new ReadOnlyCollection<string>(employeeList);
}
public void DisplayEmployees()
{
foreach (var employee in Employees)
{
Console.WriteLine(employee);
}
}
}
public class Program
{
public static void Main(string[] args)
{
EmployeeManager manager = new EmployeeManager();
manager.DisplayEmployees();
// Attempting to modify the ReadOnlyCollection will throw an exception
// manager.Employees.Add("Charlie Brown"); // This will cause a runtime error
manager.AddEmployee("Charlie Brown");
Console.WriteLine("After adding Charlie:");
manager.DisplayEmployees();
}
}
Concepts Behind the Snippet
`ReadOnlyCollection
Real-Life Use Case
Configuration settings are often stored in a collection. You might want to expose these settings to other parts of your application for reading, but prevent them from being modified after initialization. `ReadOnlyCollection
Best Practices
Interview Tip
Be prepared to explain the difference between `ReadOnlyCollection
When to Use Them
Use `ReadOnlyCollection
Memory Footprint
The memory footprint of `ReadOnlyCollection
Alternatives
Pros
Cons
FAQ
-
What happens if I try to modify a `ReadOnlyCollection
`?
A `NotSupportedException` will be thrown. -
Is `ReadOnlyCollection
` truly immutable?
No, it's not. The underlying list can still be modified from within the class that owns it. It only prevents modification from external code. -
How do I update the `ReadOnlyCollection
` if the underlying list changes?
You need to create a new `ReadOnlyCollection` instance with the updated list.