.NET/C#: some starting posts on the `yield` keyword.
Posted by jpluimers on 2013/08/08
Peter Leslie Morris asked if Delphi already incorporates the `yield` keyword that C# had introduced in C# 2.
Delphi doesn’t, but for the people interested what it does in C#:
Basically `yield` is syntactic sugar to make it a lot easier to write methods that return enumerators of some sort.
It delays (hence the yield keyword) execution until the enumerator as actually being used.
It is one of the hardest C# things to master (it is the most complicated transformation in the compiler, followed by anonymous methods – well maybe with the exception of async/await), but it can be very useful.
VB.NET doesn’t have it either (thanks André!) has it too, but and also has iterator blocks.
Some start posts on yield:
- What is the yield keyword used for in C#? – Stack Overflow.
- Behind the scenes of the C# yield keyword « Struggles by Lars C..
–jeroen
.NET/C#: some starting posts on the `async` and `await` keywords « The Wiert Corner – irregular stream of stuff said
[…] year’s summer, I posted some .NET/C#: some starting posts on the
yield
keyword and mentioned thatasync
andawait
might be the most complicated compiler […]André Obelink said
VB.NET has – similar to C# – the Yield keyword…
Sub Main()
For Each number As Integer In SomeNumbers()
Console.Write(number & ” “)
Next
‘ Output: 3 5 8
Console.ReadKey()
End Sub
Private Iterator Function SomeNumbers() As System.Collections.IEnumerable
Yield 3
Yield 5
Yield 8
End Function
http://msdn.microsoft.com/en-us/library/vstudio/dscyy5s0.aspx
jpluimers said
Great. I stand corrected.
Stefan Glienke said
Delphi has yield return ;) See http://delphisorcery.blogspot.de/2011/04/yield-return-and-delphi.html
It is implemented for win32 and win64 using the fiber winapi.
jpluimers said
Wow, that is COOL!
Any chance of making that X-platform?
–jeroen
Stefan Glienke said
Only if someone points me to (or develops) a coroutine implementation for the other platforms.
Otherwise there is still the possibility to use a thread based implementation (which is of course much slower due to the context switches)
jpluimers said
Maybe ask about that on StackOverflow? Despite many moderators there thinking they are demi-Gods, it is still the best Q&A site for programmers.
Stefan Glienke said
I have a thread based implementation but at least on windows it suffers from the context switching (talking about several thousands of iterations though) whereas the fiber based implementation is almost instant.
And I haven’t tested it on other platforms than windows yet. But as it simply follows the producer/consumer pattern it should work.
jpluimers said
Well done!
jpluimers said
Thanks for the update!