Wednesday, July 17, 2019

What is Yield in C# and when to use it

Yield is a keyword in C# which is not understood properly by many people. So what is yield? When you specify yield you'll only get next element from an iterator. Means you'll use yield with an iterator. This removes the need of an extra class or logic which holds the collection.

Simple example of usage of yield keyword



In the above example you are returning the results list. Which is an extra parameter. You can remove this by introducing yield keyword to temporary hold the value in each iteration.

By using yield you don't have to iterate the complete collection. You can breakaway from the collection using break statement. 

Good use cases of yield is when converting DataTable to IEnumerable<T>. Also see when not to use yield.


1 comment:

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook