Reputation: 6362
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;
}
}
Upvotes: 0
Views: 236
Reputation: 838876
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 of IEnumerable
.
public static IEnumerable<int> Power(int baseNumber, int highExponent)
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:
public static IEnumerable<int> Power(int baseNumber, int highExponent)
{
return Enumerable.Range(1, highExponent)
.Select(e => (int)Math.Pow(baseNumber, e));
}
The yield
keyword has not been made obsolete. If the code is clearer with yield
then use it.
Upvotes: 2