What is the purpose of Yield and how does it work?
The compiler turns this code into an enumerator. You can use this enumerator to iterate over the sequence {1, -1}
:
foreach(var i in ClassName.RightAndLeft)
Console.WriteLine(i);
results in
1
-1
Note that this property does not have two return statements and return type int
. It returns an IEnumerable<int>
, a sequence containing 1
and -1
.
See yield keyword for more information.
One important part to note is that the second line yield return -1;
is executed after the first value has been printed out by Console.WriteLine
in this example.
Since the poster is a game developer, he probably uses these two values as direction indicators and this enumeration to, well, enumerate all possible directions or something like that.