IReadOnlyCollection vs ReadOnlyCollection

There are several similar questions already on SO, but not one of the ones I found touches on this topic, so here it is ...

I understand that you should always try to return the interface over a specific class. I won’t go for the reasons behind this, there are a lot of things about SO about this already.

However, in the case of IReadOnlyCollectionvs a, ReadOnlyCollectionI am not sure whether this rule should be followed.

An IReadOnlyCollectioncan be easily distinguished in List, which ... well ... breaks down the aspect ReadOnlyinto contract promises.

ReadOnlyCollectionhowever cannot be added to List, but that means returning a specific class.

Ultimately, does it really matter? It seems to me that in most cases an object is ReadOnly*/IReadOnly*returned only by a returned method or a read-only property.

Thus, even if the user decides to pass it on to something else (in the case of the object IReadOnly*) or use LINQ to create some collection from it (in the case of the object ReadOnly*), there really is no way for the class displaying the object ReadOnly*/IReadOnly*to accept it back.

So, what is the recommendation here, return an interface IReadOnly*or a specific instance of a class ReadOnly*?

+4
source share
3 answers

.

, , , , :

public class QueueThing
{
    private List<QueueItem> _cantTouchThis;

    public IReadOnlyCollection<QueueItem> GetQueue()
    {
        return _cantTouchThis;
    }
}

AsReadOnly(), ReadOnlyList<T>, List<T>:

public class QueueThing
{
    private List<QueueItem> _cantTouchThis;

    public IReadOnlyCollection<QueueItem> GetQueue()
    {
        return _cantTouchThis.AsReadOnly();
    }
}

, , _cantTouchThis ( , , , ).

, , , , .

+1

IReadOnlyCollection<T> List<T>, . ReadOnlyCollection<T> , IReadOnlyCollection<T>.

, , IReadOnlyCollection<T>, , -, , , ReadOnlyCollection<T>

public IReadOnlyCollection<User> GetUsers()
{
   return new ReadOnlyCollection<User>();
}


IReadOnlyCollection<T> , , .
, ReadOnlyCollection<T>, .
- , .

+8

Microsoft manuals here state:

✓ Use ReadOnlyCollection , a subclass, ReadOnlyCollection<T>or in rare cases IEnumerable<T>for properties or return values ​​that represent read-only collections.

So, in principle, you should return ReadOnlyCollection<T>. It indicates the interface IEnumerablein other cases, so if it was intended for the interface IReadOnlyCollection<T>, he would say that.

0
source

Source: https://habr.com/ru/post/1681685/


All Articles