Why does IEnumerable.ToList() return List instead of IList?

前端 未结 10 1721
暖寄归人
暖寄归人 2020-12-29 02:23

The extension method ToList() returns a List. Following the same pattern, ToDictionary() returns a Dictionary<

10条回答
  •  旧巷少年郎
    2020-12-29 02:28

    This is one of the common things that programmers have difficulty understanding around the use of interfaces and concrete types.

    Returning a concrete List that implements IList only gives the method consumer more information. Here is what the List object implements (via MSDN):

    [SerializableAttribute]
    public class List : IList, ICollection, IList, ICollection, 
        IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable
    

    Returning as a List gives us the ability to call members on all of these interfaces in addition to List itself. For example we could only use List.BinarySearch(T) on a List, as it exists in List but not in IList.

    In general to maximize flexibility of our methods, we should take the most abstract types as parameters (ie. only the things we're going to use) and return the least abstract type possible (to allow a more functional return object).

提交回复
热议问题