IList, ICollection, or IEnumerable in a service interface?

I am creating a service to access my database with the Entity Framework in ASP.NET MVC 5. Therefore, I am writing first a basic service with its interface. But I'm worried about a little thing.

I usually return IEnumerable<T>to my interface, but this often leads to calls ToList()in the code.

Therefore, I was wondering what is the best way to return in such an interface. I could just come back IList, but I'm afraid that it might be too much, and that I will not need all the methods provided IList.

Here is my code:

public interface IBaseService<T>
{
    T Add(T obj);
    T Update(T obj);
    T Remove(string id);
    T Get(string id);

    ICollection<T> Find(Expression<Func<bool, T>> func);
    ICollection<T> GetAll();
}
+4
source share
3 answers

you said, that

IEnumerable , ToList() .

, ToList() . , , (/ ). , , Find GetAll, ICollection<T> IList<T> ( \ ).

, ToList \ . Count - return IReadOnlyCollection<T>, IEnumerable<T> Count. indexer - return IReadOnlyList<T>, IReadOnlyCollection<T> .

Array List<T> , , :

 static IReadOnlyList<string> Test() {
      return new string[0]; // fine
 }

, List - IList<T> . , , AsReadOnly ( , ):

static IReadOnlyList<string> Test() {
      return new List<string>().AsReadOnly(); // not required but good practice
 }
+4

. IReadOnlyCollection<T>. , , , ICollection<T>. IEnumerable<T>, , .

+2

, IEnumerable<T>, . , List<T> .

+1

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


All Articles