How to make List's Add method protected, while exposing List with get property?
As others have said, you are looking for the .AsReadOnly()
extension method.
However, you should store a reference to the collection instead of creating it during each property access:
private readonly List<SomeOtherClass> _items;
public WhatClass()
{
_items = new List<SomeOtherClass>();
this.Items = _items.AsReadOnly();
}
public ReadOnlyCollection<SomeOtherClass> Items { get; private set; }
This is to ensure that x.Items == x.Items
holds true, which could otherwise be very unexpected for API consumers.
Exposing ReadOnlyCollection<>
communicates your intent of a read-only collection to consumers. Changes to _items
will be reflected in Items
.
You're looking for the ReadOnlyCollection<T>
class, which is a read-only wrapper around an IList<T>
.
Since the ReadOnlyCollection<T>
will reflect changes in the underlying list, you don't need to create a new instance every time.
For example:
public class WhatClass {
public WhatClass() {
_SomeOtherClassItems = new List<SomeOtherClass>();
SomeOtherClassItems = _SomeOtherClassItems.AsReadOnly();
}
List<SomeOtherClass> _SomeOtherClassItems;
public ReadOnlyCollection<SomeOtherClass> SomeOtherClassItems { get; private set; }
}
Use List<T>.AsReadOnly
:
public ReadOnlyCollection<SomeOtherClass> SomeOtherClassItems
{
get
{
return _SomeOtherClassItems.AsReadOnly();
}
}
This will return a ReadOnlyCollection, which will throw an exception if a client calls Add through the interface. In addition, the ReadOnlyCollection type does not expose a public Add method.