Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generators in C#?

In javascript I can create a generator which would behave like this:

function* idMaker(){
  var index = 0;
  while(true)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

What would the C# equivalent look like?

I wonder whether this will work:

static System.Collections.Generic.IEnumerable<int> MakeId()
{
  int index = 0;
  while (true)
    yield return index++;
}

but from what I understand of C# so far, the above wouldn't work as I intend and instead infinite loop.


1 Answers

You can do the same with your MakeId in the following way:

using (var gen = MakeId().GetEnumerator()) {
    gen.MoveNext();
    Console.WriteLine(gen.Current); // 0
    gen.MoveNext();
    Console.WriteLine(gen.Current); // 1
    gen.MoveNext();
    Console.WriteLine(gen.Current); // 2
}

If you don't like to call MoveNext all the time, you can write extension method:

public static class Extensions {
    public static T NextValue<T>(this IEnumerator<T> enumerator) {
        enumerator.MoveNext();
        return enumerator.Current;
    }
}

Then it becomes

using (var gen = MakeId().GetEnumerator()) {                
    Console.WriteLine(gen.NextValue()); // 0                
    Console.WriteLine(gen.NextValue()); // 1                
    Console.WriteLine(gen.NextValue()); // 2
}
like image 185
Evk Avatar answered Sep 04 '25 23:09

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!