Why do we need Yield Keyword in C#?
what is the exact use of yield keyword in C#?
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Nov 2, 2020, 2:51 AM EST
now you are asked to create a method to return all numbers greater than 7 , and you are not allowed to use Linq.
so when we are not allowed to use Linq , then creating a method which return some entity out of many , unnecessarily forces us to create another temperory List to hold such values
ex
As you can see , we are unnecessaryliy creating Temperory List.
Yield solves this problem
so , you can see we are not creating temperory List.
How Yield successfully solves the problem?
Ans:- Yield does stateful iteration , meaning it remembers the last location from where he has to iterate everytime.