Skip to content

Instantly share code, notes, and snippets.

@MarkPflug
Created October 12, 2021 22:37
Show Gist options
  • Save MarkPflug/4fd5717b80f6283ada9269d7a308a2e6 to your computer and use it in GitHub Desktop.
Save MarkPflug/4fd5717b80f6283ada9269d7a308a2e6 to your computer and use it in GitHub Desktop.
Stupid array trick
static class Program
{
public static void Main()
{
int[] data = new int[12];
// foreach over refs to the elements of the array
foreach(ref int elem in data.Refs())
{
elem = 1;
}
}
}
static class ArrayExtensions
{
public static ArrayEnumerable<T> Refs<T>(this T[] arr)
{
return new ArrayEnumerable<T>(arr);
}
}
struct ArrayEnumerable<T>
{
T[] arr;
int idx;
public ArrayEnumerable(T[] arr)
{
this.arr = arr;
this.idx = -1;
}
public ArrayEnumerable<T> GetEnumerator() {
return this;
}
public bool MoveNext()
{
if(++idx < arr.Length)
{
return true;
}
return false;
}
public ref T Current
{
get
{
return ref arr[idx];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment