P
P
Prizm2021-11-22 00:32:41
C++ / C#
Prizm, 2021-11-22 00:32:41

Static arrays and templates by number in C#?

This is not the first time I have encountered a problem: in C# I need to implement a class, one of whose methods must return a small array of N = ~5 float. Moreover, for each individual instance N = const. I could just return a dynamic array, but as I noticed from the measurements, allocating memory for a small array and deleting it takes a lot of time (at least in a Debug build). Elsewhere, I replaced new with stackalloc, and this speeded up the method by about half. I would like to apply something similar for a few other classes as well, for example:

class ConnectedPoint : Point {
    public ConnectedPoint[] nbs;
    public short[] ids;
    public ConnectedPoint(Vector2 center_) : base(center_) {
        nbs = new ConnectedPoint[4] { null, null, null, null };
        ids = new short[4] { 0, 0, 0, 0 };
    }
...
}

Well, as described above, I would like to apply something similar to return a small array of elements.
So - how to implement something similar within C#? With C++ it would be easy, I could use float vals[4]; and template class someClass{...};, but in C# I did not find any normal static arrays, nor templates with a non-type.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-11-22
@PrizmMARgh

There are no const generics in C#.
And no arrays have a fixed, at compile-time, length.
Alternatively, you can stackalloc on the caller and pass the Span to the method to fill it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question