OK, so List<> contains the AsReadOnly() which gives you the ReadOnlyCollection. What I need is to have a field of IList type, and a property which would return a ReadOnlyCollection for this list.
Example class:
class Test
{
private IList<Abc> list;
public AddToList(Abc someItem) { /* adds inside the list */... }
public ReadOnlyCollection<Abc> List { get { return ??? } } // <- no "set" here!
}
The scenario is following: I need to have some custom logic inside my class when the item is added into the list, and I want to restrict adding to this list by calling AddToList(someitem), while not allowing the usage of list.Add(someItem). The problem is that I use NHibernate which requires the IList interface, so I cannot cast / call the AsReadOnly() on the IList (it does not contain this method).
What way would you recommend to solve this situation? I simply need a way for NHibernate to set the needed collection in some way, but I also need to restrict users.
Generally best practice is to accept parameters of the most generic type and to return the most specific. However, conventionally programmers tend to not want to tie themselves to the List implementation and normally return the IList interface.
We can make Collections object Read-Only by using unmodifiableCollection() and to make Map Read-Only we can use unmodifiableMap() method. This method accepts any of the collection objects and returns an unmodifiable view of the specified collection.
An instance of the ReadOnlyCollection<T> generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface.
You can just emulate AsReadOnly()
:
public ReadOnlyCollection<Abc> List
{
get { return new ReadOnlyCollection<Abc>(list); }
}
UPDATE:
This doesn't create a copy of list
. ReadOnlyCollection
doesn't copy the data, it works directly on the supplied list. See documentation:
A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
This constructor is an O(1) operation.
try
return new ReadOnlyCollection<Abc> (list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With