Difference between yield in Python and yield in C#

Viewed 4937

What is the difference between yield keyword in Python and yield keyword in C#?

3 Answers

An important distinction to note, in addition to other answers, is that yield in C# can't be used as an expression, only as a statement.

An example of yield expression usage in Python (example pasted from here):

def echo(value=None):
  print "Execution starts when 'next()' is called for the first time."
  try:
    while True:
       try:
         value = (yield value)
       except GeneratorExit:
         # never catch GeneratorExit
         raise
       except Exception, e:
         value = e
     finally:
       print "Don't forget to clean up when 'close()' is called."

generator = echo(1)
print generator.next()
# Execution starts when 'next()' is called for the first time.
# prints 1

print generator.next()
# prints None

print generator.send(2)
# prints 2

generator.throw(TypeError, "spam")
# throws TypeError('spam',)

generator.close()
# prints "Don't forget to clean up when 'close()' is called."
Related