Skip to content

Instantly share code, notes, and snippets.

@savaged
Created November 15, 2022 16:47
Show Gist options
  • Save savaged/72142a3dff4680f2df39de6c721d40f7 to your computer and use it in GitHub Desktop.
Save savaged/72142a3dff4680f2df39de6c721d40f7 to your computer and use it in GitHub Desktop.
Example of duck typing with Ranges from Nick Chapsas
// 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