Friday, November 13, 2009

Wacky C#: yield return

Right off from the canonical "C# Language Specification".

static IEnumerable Range(int from, int to) {
for (int i = from; i < to; i++) {
yield return i;
}
yield break;
}
static void Main() {
foreach (int x in Range(-10,10)) {
Console.WriteLine(x);
}
}

What the heck is "yield return"? The purity of return statement is whacked. It seems each yield return is for each of the items in that IEnumerable.

I saw this example too, in another place, where Fib is of course the (fabulous) Fibonacci numbers:

public static IEnumerable Fib(int a, int b)
{
yield return 1;
yield return 1;
yield return 2;
yield return 3;
yield return 5;

}

static void Main()
{
foreach (int i in Fib(1, 5))
{
Console.WriteLine("{0} ", i);
}
}

I'll list more wackiness when I see them

3 comments:

Alex Mak said...

C# is so not a Java copycat that many people believe it to be.

C# has its oddities, but it is the best language to develop for Windows, still and possibly forever will be the dominant platform. Therefore, we programmers must learn C#.

Not every app runs on the web.

yield is an unfamiliar feature not entirely without merit.

Anonymous said...

Good fill someone in on and this mail helped me alot in my college assignement. Thanks you as your information.

Anonymous said...

Opulently I agree but I contemplate the list inform should have more info then it has.