Is it bad form to return Arrays in C#? Should I return List?

后端 未结 7 1077
南方客
南方客 2020-12-14 20:31

I have a function which returns a variable number of elements, should I return an array or a List? The \"collection\'s\" size does not change once returned, ie for all purpo

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 21:21

    It's bad form to return arrays if not needed, and especially to return List.

    Usually, you'll want to return IEnumerable or IList.

    If your user is going to just need to run through each element, IEnumerable will provide this capability. It also allows you to potentially implement the routine (now or later) using deferred execution.

    If your user needs to access elements by index, return IList. This provides all of the benefits of arrays, but gives you more flexibility in your implementation. You can implement it as an array, a list, or some other collection that implements IList, and you don't have to convert/copy to an array.

提交回复
热议问题