Why use a
IReadOnlyList<T>
and not an
IList<T>
or
List<T>
?
IReadOnlyList<T>
guards against the content of the list being altered. So you cannot modify (Add/Remove) items, only modify their content if the items allow it.
UPDATE
As mentioned above, you can not Add or Remove items from a
IReadOnlyList<T>
. You need to replace the list.
Here is an example:
<pre>var items = new List<string>
{
"one",
"two",
"three"
};
var test = new TestClass(items);
foreach (string item in test.ReadOnlyList)
{
Console.WriteLine(item);
}
Console.WriteLine("-----");
var newItems = new List<string>(items);
newItems.Reverse();
test.SetReadonlyList(newItems);
foreach (string item in test.ReadOnlyList)
{
Console.WriteLine(item);
}
Console.WriteLine("-----");
class TestClass
{
public IReadOnlyList<string> ReadOnlyList { get; set; }
public TestClass(List<string> items)
{
ReadOnlyList = items.ToList();
}
public void SetReadonlyList(List<string> items)
{
ReadOnlyList = items;
}
}