How can the yield return be refactored in .NET 4.0
public static void DoIt()
{
foreach (int n in Power(2,4))
{
Console.Write(n);
}
}
public static IEnumerable CalcPower(int base, int exponent)
{
int res = 1;
for (int c = 1; c <= high; counter++)
{
res = res * base;
yield return result;
}
}
Your approach is fine. That’s probably the way I’d implement it too. One change is that you should use the generic
IEnumerable<int>instead ofIEnumerable.If you really want to do it another way, you can use LINQ, but in my opinion, it’s not as clear as the original code:
The
yieldkeyword has not been made obsolete. If the code is clearer withyieldthen use it.