Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NoCheroot/576102573ece867c031aa79a93a2e6ea to your computer and use it in GitHub Desktop.
Save NoCheroot/576102573ece867c031aa79a93a2e6ea to your computer and use it in GitHub Desktop.
Implementing IEnumerator<T> in PowerShell

In order to implement IEnumerator<T> you have to explicitly implement the Current member for IEnumerator<T> and IEnumerator ... but PowerShell won't let you have two different implementations of the same property, nor will it let you explicitly implement an interface member. So we do one at a time, like this:

First, make a non-generic IEnumerator, but implemented with the type you want in the end:

    class __Generator : System.Collections.IEnumerator {
        [int]$Actual = 0

        [object]get_Current() {
            return $this.Actual
        }

        [bool] MoveNext() {
            $this.Actual = Get-Random
            return $true
        }

        [void] Reset() {
            $this.Actual = 0
        }

        [void] Dispose() {
            # Do nothing
        }
    }

Then, you implement the specific generic type:

    class Generator : __Generator, System.Collections.Generic.IEnumerator[int] {
        [int]get_Current() {
            return $this.Actual
        }
    }

Now you can actually use the generator class however you like:

    [Generator]::new() | Select -First 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment