Search code examples
c#arraysclasssyntax

Is it possible to use a C like array in C#?


I want to create a class that is basically just a fixed size array with some functions to it.
This would be done like this:

private class SomeClass : SomeSuperClass {
    private readonly SomeType[] children = new SomeType[256];
    ...
}

Now this would work logically. But I think this will make the array a seperate heap object, which I do not want.
I would much rather let it behave, as if I would be doing the following in C++:

class SomeClass : SomeSuperClass {
    SomeType children[256];
    ...
}

Is there any way of doing this in C# or do I have to rely on my compiler to know to optimize this?
It is not a big problem, but it does bother me and I could not find anything about this on my own.


Solution

  • As @EtiennedeMartel commented, you can use an inline array for this:

    Inline arrays are used by the runtime team and other library authors to improve performance in your apps. Inline arrays enable a developer to create an array of fixed size in a struct type. A struct with an inline buffer should provide performance characteristics similar to an unsafe fixed size buffer.

    An example in your case:

    [System.Runtime.CompilerServices.InlineArray(256)]
    public struct ChildrenArray
    {
        private SomeType _element0;
    }
    
    private class SomeClass : SomeSuperClass {
        private readonly ChildrenArray children = new ChildrenArray();
        //...
    }
    

    children[i] will give you access to the ith element, just like with a normal array.

    Note: it is available since C# 12.