Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a collection of readonly ref struct

Tags:

c#

.net

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?

like image 429
heapoverflow Avatar asked Oct 23 '25 18:10

heapoverflow


2 Answers

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.

like image 133
MikeJ Avatar answered Oct 26 '25 06:10

MikeJ


You can't, ref struct cannot be stored in a collection. I found this which might be helpful to you.

Gergely Kalapos

like image 25
Chase Meyer Avatar answered Oct 26 '25 06:10

Chase Meyer