Monday, December 14, 2020

Where it is preferred to use yield return in c#?

 Is it just because it saves me a row of a list declaration?


No. When you use yield you get Deferred Execution. This means that you create the items to yield as the consumer is consuming the items.

If you add items to the list and then return it, then you have to create all items before the consumer can consume any of them.

For example, assume that the consumer calls your method and uses a for loop to consume it like this:

foreach(var item in GetMyLovelyItems())
{
   ...
}

If the GetMyLovelyItems returns a list, then all items will be created before the GetMyLovelyItems method returns and the loop starts.

If on the other hand, you use yield to return items, then the items will be created as the loop goes from one iteration to the next one.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...