Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Last active December 8, 2021 10:27
Show Gist options
  • Save sonnemaf/94184e19b37896a6751b3542574338c7 to your computer and use it in GitHub Desktop.
Save sonnemaf/94184e19b37896a6751b3542574338c7 to your computer and use it in GitHub Desktop.
var l = new List<PointStruct>() {
new PointStruct(1, 10),
new PointStruct(2, 20),
new PointStruct(3, 30),
};
var a = l.ToArray();
l.ForEachRef(static (ref PointStruct p) => p.Swap());
foreach (var p in l) {
Console.WriteLine(p);
}
static class Extensions {
public delegate void RefAction<T>(ref T value) where T : struct;
public static void ForEachRef<T>(this List<T> list, RefAction<T> action) where T : struct {
if (list is null) throw new ArgumentNullException(nameof(list));
if (action is null) throw new ArgumentNullException(nameof(action));
var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(list);
foreach (ref T item in span) {
action(ref item);
}
}
}
struct PointStruct {
public int X, Y;
public PointStruct(int x, int y) {
X = x;
Y = y;
}
public void Swap() => this = new PointStruct(Y, X);
public double Dist => Math.Sqrt((X * X) + (Y * Y));
public override string ToString() => $"({X.ToString()},{Y.ToString()})";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment