To prevents clients from assigning a brand new collection, use a private field (readonly
if applicable) and a public get-only property.
private readonly IList<T> _items = new List<T>();
public IList<T> Items
{
get { return _items; }
}
To prevent clients from assigning a brand new collection and modifying your collection, use IReadOnlyCollection<T>
public MyClass()
{
List<T> list = //new list
_items = new ReadOnlyCollection<T>(list);
}
private readonly IReadOnlyCollection<T> _items;
public IReadOnlyCollection<T> Items
{
get { return _items; }
}
Returning a list as an IEnumerable<T>
is not a very reliable option. The client can simply downcast the enumerable back to a list, and mutate. You should wrap the mutable list in a ReadOnlyCollection<T>
.