Return all enumerables with yield return at once; without looping through

前端 未结 6 1702
甜味超标
甜味超标 2020-11-29 03:55

I have the following function to get validation errors for a card. My question relates to dealing with GetErrors. Both methods have the same return type IEnumerable&

6条回答
  •  一个人的身影
    2020-11-29 04:28

    Yes it is possible to return all errors at once. Just return a List or ReadOnlyCollection.

    By returning an IEnumerable you're returning a sequence of something. On the surface that may seem identical to returning the collection, but there are a number of difference, you should keep in mind.

    Collections

    • The caller can be sure that both the collection and all the items will exist when the collection is returned. If the collection must be created per call, returning a collection is a really bad idea.
    • Most collections can be modified when returned.
    • The collection is of finite size.

    Sequences

    • Can be enumerated - and that is pretty much all we can say for sure.
    • A returned sequence itself cannot be modified.
    • Each element may be created as part of running through the sequence (i.e. returning IEnumerable allows for lazy evaluation, returning List does not).
    • A sequence may be infinite and thus leave it to the caller to decide how many elements should be returned.

提交回复
热议问题