Skip to content

Instantly share code, notes, and snippets.

@mgravell
Last active August 6, 2020 09:47
Show Gist options
  • Save mgravell/db3e63c2f8cea1866a6aaade7507fa18 to your computer and use it in GitHub Desktop.
Save mgravell/db3e63c2f8cea1866a6aaade7507fa18 to your computer and use it in GitHub Desktop.
readonly struct Foo
{
private readonly int[] _arr;
public Foo(int length) => _arr = new int[length];
public int Length => _arr?.Length ?? 0;
public ref int this[int index] => ref _arr[index];
public FooEnumerator GetEnumerator() => new FooEnumerator(_arr);
public struct FooEnumerator
{
private readonly int[] _arr;
private readonly int _length;
private int _index;
public FooEnumerator(int[] arr)
{
_arr = arr;
_length = arr.Length;
_index = -1;
}
public bool MoveNext() => ++_index < _length;
public ref int Current => ref _arr[_index];
}
static void Main()
{
var obj = new Foo(8);
for (int i = 0; i < obj.Length; i++)
obj[i] = i;
foreach (ref int value in obj)
{
System.Console.WriteLine(value);
value *= 2;
}
System.Console.WriteLine("====");
foreach (int value in obj)
System.Console.WriteLine(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment