Created
November 15, 2022 16:47
-
-
Save savaged/72142a3dff4680f2df39de6c721d40f7 to your computer and use it in GitHub Desktop.
Example of duck typing with Ranges from Nick Chapsas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Full credit to Nick Chapsas - See: https://youtu.be/jmmz1cInNow | |
foreach (var i in 0..5) | |
{ | |
Console.WriteLine(i); | |
} | |
public static class Extensions | |
{ | |
public static CustomIntEnumerator GetEnumerator(this Range range) => new CustomIntEnumerator(range); | |
public static CustomIntEnumerator GetEnumerator(this int i) => new CustomIntEnumerator(new Range(0, i)); | |
} | |
public ref struct CustomIntEnumerator | |
{ | |
private int _current; | |
private readonly int _end; | |
public CustomIntEnumerator(Range range) | |
{ | |
if (range.End.IsFromEnd) | |
throw new NotSupportedException(); | |
_current = range.Start.Value - 1; | |
_end = range.End.Value; | |
} | |
public int Current => _current; | |
public bool MoveNext() => ++_current <= _end; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment