Yield we will use when we want to return a collection (i.e. IEnumerable).
For example small console application:
namespace Yield { using System; using System.Collections.Generic; class Program { static void Main(string[] args) { IEnumerable<string> aaa; foreach (var a in YieldTest()) { Console.WriteLine(a); } Console.ReadKey(); } private static IEnumerable<string> YieldTest() { string[] myTestsStrings = new[] { "One", "Two" }; foreach (var myTest in myTestsStrings) { yield return myTest; } } } }
As a result we will see something like:
One
Two
Note line:
yield return myTest;
If we remove "yield" from that line, we will receive the error:
Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable<string>'
Our YieldTest method can look like:
private static IEnumerable<string> YieldTest() { string[] myTestsStrings = new[] { "One", "Two" }; foreach (var myTest in myTestsStrings) { return new[] { myTest }; } return null; }
Notice that instead of:
yield return myTest;
Now we have:
return new[] { myTest };
Which will give as result something like:
One
Just one record.