How to you implement Deferred Execution?

Deferred execution is a technique in which the evaluation of an expression is delayed until the point where its resultant value is actually used.
  • Deferred execution is a technique in which the evaluation of an expression is delayed until the point where its resultant value is actually used.
  • This results in the resultant set not being placed in the application memory until its required, which can improve performance.
  • In C#, deferred execution can be created by using a yield keyword while returning a collection. The requirement is that the return type of method where yield keyword is used must be of IEnumerable or IEnumerable.
  • The yield keyword returns one single processed object from the collection when used inside an iterator instead of the entire set. It is particularly useful when the collection is particularly huge.
public IEnumerable<int> GetOdds(int upperLimit) 
{
    for(int i = 1; i <= upperLimit; i++) 
    {
        if(i%2 != 0) yield return i;
    }
}
Learn more about yield keyword here
Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply

Your email address will not be published. Required fields are marked *