Junior — Middle
Can you explain what the IReadOnlyList interface in C# is and how to use it?
sobes.tech AI
Answer from AI
The IReadOnlyList<T> interface in C# represents a collection of elements that can be accessed by index but cannot be modified (i.e., adding, removing, or changing elements). This ensures data safety when you need to pass a list for reading without the risk of modification.
Example of usage:
IReadOnlyList<int> numbers = new List<int> {1, 2, 3};
int first = numbers[0]; // access by index
// numbers[0] = 10; // compile error, as the collection is read-only
Thus, IReadOnlyList<T> is convenient to use when you need to provide access to data without the ability to modify it.