With the new readonly instance member features in C# 8, I try to minimize unnecessary copying of struct
instances in my code.
I do have some foreach
iterations over arrays of structs, and according to this answer, it means that every element is copied when iterating over the array.
I thought I could simply modify my code now to prevent the copying, like so:
// Example struct, real structs may be even bigger than 32 bytes.
struct Color
{
public int R;
public int G;
public int B;
public int A;
}
class Program
{
static void Main()
{
Color[] colors = new Color[128];
foreach (ref readonly Color color in ref colors) // note 'ref readonly' placed here
Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
}
}
This sadly does not compile with
CS1510 A ref or out value must be an assignable variable
However, using an indexer like this compiles:
static void Main()
{
Color[] colors = new Color[128];
for (int i = 0; i < colors.Length; i++)
{
ref readonly Color color = ref colors[i];
Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
}
}
Is my syntax in the foreach
alternative wrong, or is this simply not possible in C# 8 (possibly because of how the enumeration is implemented internally)?
Or is C# 8 applying some intelligence nowadays and does no longer copy the Color
instances by itself?