Introduction
Yield statement appears inside the iterator block. It basically use to provide the value to the enumerator object.
Use
VB.NET
Yield statement is used inside the iterator block to provide value to enumerator object.Code
Logically it can be used for representing the end of the iteration block.
Basically it can be used in one of the following formCode
yield return <expression>;Code
yield break;Code
Yield statement may be use as a body of a method ,accessor or operator.Code
Body of these type of methods define with following restrictions:
Unsafe block should not be there.
Method parameter should not have ref or out.Code
The one important point about the yield statement is that it can not be used in an anonymous method.Code
ExampleC#
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int n, int exp)
{
int count = 0;
int res = 1;
while (count++ < exp)
{
res = res * n;
yield return res;
}
}
static void Main()
{
foreach (int z in Power(2, 8))
{
Console.Write("{0}", z);
}
}
}

Join the conversation! Your thoughts help the community grow.