IEnumerable as return type

前端 未结 10 2268
轮回少年
轮回少年 2020-12-01 10:41

Is there a problem with using IEnumerable as a return type? FxCop complains about returning List (it advises returning Coll

10条回答
  •  爱一瞬间的悲伤
    2020-12-01 11:18

    This is really a two part question.

    1) Is there inherently anything wrong with returning an IEnumerable

    No nothing at all. In fact if you are using C# iterators this is the expected behavior. Converting it to a List or another collection class pre-emptively is not a good idea. Doing so is making an assumption on the usage pattern by your caller. I find it's not a good idea to assume anything about the caller. They may have good reasons why they want an IEnumerable. Perhaps they want to convert it to a completely different collection hierarchy (in which case a conversion to List is wasted).

    2) Are there any circumstances where it may be preferable to return something other than IEnumerable?

    Yes. While it's not a great idea to assume much about your callers, it's perfectly okay to make decisions based on your own behavior. Imagine a scenario where you had a multi-threaded object which was queueing up requests into an object that was constantly being updated. In this case returning a raw IEnumerable is irresponsible. As soon as the collection is modified the enumerable is invalidated and will cause an execption to occur. Instead you could take a snapshot of the structure and return that value. Say in a List form. In this case I would just return the object as the direct structure (or interface).

    This is certainly the rarer case though.

提交回复
热议问题