It is not possible to create an array of a readonly ref struct in C# like this:
public readonly ref struct SomeStruct {}
SomeStruct[] array = new SomeStruct[4];
This throws a compilation error.
How is it possible to store a collection of readonly ref struct?
I think this is what you're after:
struct SomeStruct
{
int Data;
}
static void Main(string[] _)
{
Span<SomeStruct> buffer = stackalloc SomeStruct[5];
ref var someData = ref buffer[1];
}
I would caution that you need to profile and make sure you actually need to do something like this.
As others have said you don't put a "ref struct" into a collection instead you put regular structs in the collection and get a "ref" to them so you don't have to copy the data. Then you control where you allocate them. Either on the stack if it's not going to cause problems, or you could use memory pools.
You can't, ref struct cannot be stored in a collection. I found this which might be helpful to you.
Gergely Kalapos
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With