Skip to end of metadata
Go to start of metadata

Still having problems understanding generators, huh?

Don't worry - its easy stuff.

The basic syntax is:

In practice, it generally looks like this:

Let's start off easy:

After the generator expression is run, <local variable> will become an enumerable object that you can iterate through, like an array, list, or collection. The contents of this enumerable object will be a collection of <expression>s.

<expression>s are variables that are put into <local variable> if <conditional expression> returns true. This means means that by using a <conditional expression> in a generator, you can decide which objects should be added to the enumerable <local variable>. <expressions> can be manipulated further: for instance, this syntax is valid:

In this instance, the return value of MethodToMutilateExpression will be added to the enumerable <local variable>. This makes generators useful to filter the input that MethodToMutilateExpression() will be called with.

"for <declarations> in <iterator>" is your typical for loop: "for item in collection," in otherwords.

Here's a simple working example of how generators work.

Here's the output:

  • No labels