Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created April 27, 2016 01:48
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jaykul/dfc355598e0f233c8c7f288295f7bb56 to your computer and use it in GitHub Desktop.
Save Jaykul/dfc355598e0f233c8c7f288295f7bb56 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