IReadOnlyListnumbers = new List { 1, 2, 3, 4, 5 }; Console.WriteLine(numbers[0]); // Output: 1 Console.WriteLine(numbers.Count); // Output: 5
public class Person { public string Name { get; set; } public int Age { get; set; } } ListIn this example, a read-only list of Person objects is created using the AsReadOnly() method of the Listpeople = new List { new Person { Name = "John", Age = 30 }, new Person { Name = "Jane", Age = 25 } }; IReadOnlyList readOnlyPeople = people.AsReadOnly(); Console.WriteLine(readOnlyPeople[0].Name); // Output: John