Yield statement can be used in Iterator block and return value to Enumerator Object. This statement was first introduced in dotnet framework 2.0. You can use Yield return or yield break in your Iterator block. Yield break statement you can use to stop execution of iterator block with no return value. This can be used with LINQ query (see below example).
Here are some restrictions for using yield statement.
- Yield statement can be added only inside Iterator Block.
- You cannot use Yield statement inside Anonymous Method or Lambda Expression.
- You can’t use “return” statement in iterator block instead you must use “yield break” statement.
- You can’t use Yield statement in Try block with catch but you can use it in Try block with finally.
- You can’t write Yield statement in finally block of your try…catch statement.
- You can’t pass parameters as ref or out to Iterator method.
public partial class YieldStatement : Window
{
public YieldStatement()
{
InitializeComponent();
foreach (int k in Square(10))
{
Console.Write(k.ToString() + " ");
}
}
public IEnumerable<int> Square(int limit)
{
for (int i = 1; i <= limit; i++)
{
yield return i * i;
}
}
}
Output
1 4 9 16 25 36 49 64 81 100
public partial class YieldStatement : Window
{
public YieldStatement()
{
InitializeComponent();
var result = from string s in GetValues(true)
where s.Length > 3
select s;
foreach (string s in result)
{
Console.WriteLine(s);
}
}
public IEnumerable<string> GetValues(bool stop)
{
yield return "One";
yield return "Two";
yield return "Three";
if (stop)
yield break;
yield return "Four";
yield return "Five";
}
}
Output
Three
In first example, user invokes Square method; it multiplies number and return using yield return keyword. So user will get multiplied number start from 1 to entered limit.
In second example, user will receive string values having more than three characters. I passed true as parameter so I got only “Three” as output. This is because of “yield break” statement. If I pass false as parameter then I will get “Three”, “Four” and “Five” as output.
No comments:
Post a Comment