« Previous entry | Next entry » Browse > Snippets
Skip to comments (1)
[C#] Iterators with yield
Posted by Matthijs on Jan 20 2006 @ 14:52 :: 2108 unique visits
The new C# 2.0 has some pretty cool new features. One of them is the yield keyword. It can be used to easily generate a counter or iterate through a list, the possibilities are basically endless :).
A small example:
CODE: CSHARP
static void Main(string[] args)
{
foreach (int num in inc())
{
Console.WriteLine(num);
}
}
public static IEnumerable<int> inc()
{
for (int i = 0; i < 10; i++)
yield return i;
}
/*
This will obviously output:
0
1
2
3
4
5
6
7
8
9
*/
{
foreach (int num in inc())
{
Console.WriteLine(num);
}
}
public static IEnumerable<int> inc()
{
for (int i = 0; i < 10; i++)
yield return i;
}
/*
This will obviously output:
0
1
2
3
4
5
6
7
8
9
*/
It does require you to use the IEnumerable interface (generics are also new in C# 2.0) and thus define the return type.
If you want to end the iteration prematurely you can use the "yield break;" statement:
CODE: CSHARP
public static IEnumerable<int> inc()
{
for (int i = 0; i < 10; i++)
{
yield return i;
if (i == 3) //Stupid example, but you get the point :)
yield break;
}
}
{
for (int i = 0; i < 10; i++)
{
yield return i;
if (i == 3) //Stupid example, but you get the point :)
yield break;
}
}
So it's not as flexible as for example it is with Python, but very useful non the less.
1. On Aug 09 2008 @ 04:28 priya wrote:
Anyone bought from www.belrion.com before ? heard they are a paypal world seller and are macfee secured. Appreciate some feedback from anyone ^^<a href = http://www.belrion.com/en/ffxi.htm > buy ffxi</a><br>
<a href = http://www.belrion.com/en/eq.htm> buy eq flat </a><br>
<a href = http://www.belrion.com/en/wow.htm> cheap wow gold</a><br>
<a href = http://www.belrion.com> LOTR gold</a><br>
<a href = http://www.belrion.com/en/sell.htm>buy aoc gold</a><br>
<a href = http://www.belrion.com/en/l2.htm> buy L2 adena</a><br>
<a href = http://www.belrion.com/en/gamesvr.php?cid=1&gid=3&sid=10 >buy gils</a><br>
<a href = http://www.belrion.com/en/eq.htm >cheap gold wow</a><br>