C
C#5mo ago
eid

enumerable.range vs yield return

i can't understand the different bw the iterator that has made by yield return and other iterators(normal iterator, enumerable.range iterator)
5 Replies
Pobiega
Pobiega5mo ago
Whats the confusion? you could in theory implement Enumerable.Range using yield return as such:
public static class MyEnumerable
{
public static IEnumerable<int> Range(int start, int count)
{
for (int i = start; i < start + count; i++)
{
yield return i;
}
}
}
public static class MyEnumerable
{
public static IEnumerable<int> Range(int start, int count)
{
for (int i = start; i < start + count; i++)
{
yield return i;
}
}
}
its really not more complicated than that
LasseVK
LasseVK5mo ago
What exactly is the question here? Might it be that you want to understand how a method implemented using yield return actually works?
cap5lut
cap5lut5mo ago
first of all they are called enumerators in c#/.net (linq has iterators, buts thats basically an implementation detail for them) for the difference: for yield return stuff the compiler will generate its own type that implements the IEnumerator<T> and more. thats quite a bit of code thats actually generated if u look at
MODiX
MODiX5mo ago
cap5lut
sharplab.io (click here)
public class C {
public IEnumerable<int> M() {
for (int i = 0; i < 10; i++) {
yield return i;
}
}
}
public class C {
public IEnumerable<int> M() {
for (int i = 0; i < 10; i++) {
yield return i;
}
}
}
React with ❌ to remove this embed.
cap5lut
cap5lut5mo ago
so when using Enumerable.Range() instead, the compiler would not create a new type for it, which is quite beneficial long term because not every library will have its own type to do the same thing
Want results from more Discord servers?
Add your server