In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:
IEnumerable
This link has a simple example
Even simpler examples are here
public static IEnumerable testYieldb()
{
for(int i=0;i<3;i++) yield return 4;
}
Notice that yield return won't return from the method. You can even put a WriteLine
after the yield return
The above produces an IEnumerable of 4 ints 4,4,4,4
Here with a WriteLine
. Will add 4 to the list, print abc, then add 4 to the list, then complete the method and so really return from the method(once the method has completed, as would happen with a procedure without a return). But this would have a value, an IEnumerable
list of int
s, that it returns on completion.
public static IEnumerable testYieldb()
{
yield return 4;
console.WriteLine("abc");
yield return 4;
}
Notice also that when you use yield, what you are returning is not of the same type as the function. It's of the type of an element within the IEnumerable
list.
You use yield with the method's return type as IEnumerable
. If the method's return type is int
or List
and you use yield
, then it won't compile. You can use IEnumerable
method return type without yield but it seems maybe you can't use yield without IEnumerable
method return type.
And to get it to execute you have to call it in a special way.
static void Main(string[] args)
{
testA();
Console.Write("try again. the above won't execute any of the function!\n");
foreach (var x in testA()) { }
Console.ReadLine();
}
// static List testA()
static IEnumerable testA()
{
Console.WriteLine("asdfa");
yield return 1;
Console.WriteLine("asdf");
}