I have an API that returns IEnumerable<T>
(or IEnumerable
), which is internally implemented in C# using yield return
.
A trivial example:
public class Class1
{
public IEnumerable<int> Enumerate()
{
yield return 1;
}
}
In PowerShell, I cannot call IEnumerable<T>.GetEnumerator
on the enumerable returned by the method Enumerate()
:
$cls = New-Object Class1
$enumerable = $cls.Enumerate()
Write-Host $enumerable.GetType()
$enumerator = $enumerable.GetEnumerator()
It fails with:
Cannot find an overload for "GetEnumerator" and the argument count: "0".
The $enumerable.GetType()
returns expected:
Class1+d__0
An identical code in C# works as expected.
If the method is implemented using a plain return
:
return new[] { 1 };
then there's no problem in PowerShell.
Why PowerShell does not see the GetEnumerator()
?
I have found this somewhat related question: PowerShell/GetEnumerator, but it does not really give me the answer/solution (or I do not see it).
To explain, why I want to use the IEnumerator
, instead of using PowerShell foreach
: I want to process the enumerable using parallel threads started using Start-ThreadJob
. And the enumeration is lazy and time intensive. So collecting the results to some container prior to the enumeration would have a performance penalty.