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

前端 未结 10 1671
暖寄归人
暖寄归人 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:29

    In my opinion returning a List is justified by the fact that the method name says ToList. Otherwise it would have to be named ToIList. It is the very purpose of this method to convert an unspecific IEnumerable to the specific type List.

    If you had a method with an unspecific name like GetResults, then a return type like IList or IEnumerable would seem appropriate to me.


    If you look at the implementation of the Lookup class with reflector, you'll see a lot of internal members, that are only accessible to LINQ itself. There is no public constructor and Lookup objects are immutable. Therefore there would be no advantage in exposing Lookup directly.

    Lookup class seems to be kind of LINQ-internal and is not meant for public use.

提交回复
热议问题