Not accepted: Enumerable vs List

I used to work in a team where LINQ was slightly disliked because it was supposedly difficult to debug such code. We had an agreement: after each LINQ chain, the developer creates a local variable to which he writes the result of ToArray (). Whether the array is required further down the method, or it only works with IEnumerable. Before return, the result was also cast to an array, it seems that there were no methods in the entire codebase that return or accept a collection other than an array.

Bearded Legacy! - you will think and you will be right. However, despite the fact that many years have passed since LINQ became ubiquitous, and IDEs allow you to view data in debug, some developers still have a poor idea of ​​the criteria for choosing an accept and return type when it comes to collections.

To begin with, what is the collection? Since BCL has a data type of the same name, it is important to understand that a collection is a data type designed to operate on a group of items that have some common characteristic (data type). Thus, anything that can be enumerated is a collection.

Prefer abstractions

, , . , . ,   . , , .

Lazy loading

- (  IEnumerable)  , .  IList, , .   ,  lazy loading, β€” . . , 'Lazy' , , .

IReadOnlyCollection

, ,  IArray, IReadOnlyCollection,  -. 

namespace System.Collections.Generic 
{ 
  public interface IReadOnlyCollection : IEnumerable, IEnumerable 
  { 
    int Count { get; } 
  }
}

 -  4.5,  read-only . Array, List,  IList.

 IEnumerable  … ,  IReadOnlyCollection,       List. , -   List.

 Array  IReadOnlyCollection  List, .  IList    .

null

,  ,  ,  , ,  , ,  null.  null, .  - null  0 . 1  null,  null, ,  . :

 if(myEnumerable != null) 
 { 
   foreach(var item in myEnumerable) 
   { 
   } 
 }  

,   :

foreach(var item in myEnumerable ?? Enumerable.Empty<T>()) 
{
}

IEnumerable/ICollection/IList

, , :

IEnumerable

, -,

IReadOnlyCollection : IEnumerable

-,

ICollection : IEnumerable

, (IsReadOnly)

IReadOnlyList : IReadOnlyCollection

,

IList : ICollection

,

, , . , . IEnumerable , - ICollection, IList…   .

, , , . , , IReadOnlyCollection. IEnumerable , , , β€” -. lazy loading, IList ICollection, β€”  read-only .

Web API HTTP

HTTP, , -. , , , IEnumerable IList.

, HTTP JSON -  , . , (Newtonsoft.Json, System.Text.Json), List. \ - . IEnumerable response .


, , , , .

I would be glad to amendments and additions, I recommend that you familiarize yourself with the Framework Design Guidelines for Collections .




All Articles