CSharp · Console
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Program
{
public static void Main()
{
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);
Console.WriteLine(nameof(readOnlyGroceryList) + ":");
Console.WriteLine("--------");
Console.WriteLine(string.Join("\r\n", readOnlyGroceryList));
Console.WriteLine("");
Console.WriteLine("========================================");
Console.WriteLine("");
Console.WriteLine("Add an item to the source list: Vitamins");
//readOnlyGroceryList.Add("Candy"); // Compiler Error - Items cannot be added to a ReadOnlyCollection object
groceryList.Add("Vitamins"); // ..but they can be added to the original collection
Console.WriteLine("");
Console.WriteLine("========================================");
Console.WriteLine("");
// The last item on the read only list is now "Vitamins"
Console.WriteLine(nameof(readOnlyGroceryList) + ":");
Console.WriteLine("--------");
Console.WriteLine(string.Join("\r\n", readOnlyGroceryList));
}
}