What is the use of yield keyword in C#, when we should use yield in C#.net. Will C# yield keyword boost performance of .Net code execution? Or what is the benefit of using C# keyword
These are the questioned which have in mind for most of the Micirisoft .Net developers. Some more doubts hanging there would be like why there is no Yield keyword in VB.net while C#.net has it
The exact usage of C# yield keyword is a bit tricky to understand till you see what is exactly happening behind the scene while using a yield key word in C# .net .
There are so many verifications and enhancements done by the Microsoft .Net Runtime, the CLR to enhance the performance of .Net code and actually speaking, if the developer does’t know or care about writing good code, these features creates a nightmare for him or her.
But Yield Keyword is actually a facility given by the C# compiler and the Microsoft .Net Runtime (CLR) doesn’t really know that such a keyword exist and developers are using it.
Then how C# yield keyword is working ?
C# translates or generates the yield keyword into an equalling class during compile time. This class would be having a [CompilerGenerated] .Net attribute to show that this code has been generated by the C# .net Compiler. This generated code acts as a state machine which stores the current state of the iterator in which the Yield Keyword is used. Being said that, yes the yiled keyword in C# can be used only within C# iterators and would return a IEnumerable Object. Below is the small code snippet which uses yield
IEnumerable<string> Find(IEnumerable<string> entries)
foreach(string entry in entries)
yield return entry;
In the above code what happens is whenever and entry.StartsWith(“N”) returns true, that entry is returned to the calling function.So now you will be thinking that what is the difference between just doing a return and yield return. Whenever you do a normal return the control will be exited from the current method which equallent to using a “yield break” statement here. When you use a yield return, the C# generated code which acts as the state machine will store the current position in which the match was found the returns the control. Remember while retuning we are returning an IEnumerable object and when you call this same method again while your code execution, the iterator restores the old position from the state machine and will resume the iteration from that position from where it left off last time and not from the beginning. A search from the beginning will happen only if you have exited the method using “yield break” statement
- Yield can make your code more efficient in both performance and readability factors.
- C# Yield keyword is introduced along with .NET 2.0,
If you like this post and was useful to know, Please leave your comment and like it or share with your friends.
Also let me know if this post can be improved..