Created
October 12, 2021 22:37
-
-
Save MarkPflug/4fd5717b80f6283ada9269d7a308a2e6 to your computer and use it in GitHub Desktop.
Stupid array trick
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
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