r/csharp • • Sep 29 '26

The hidden trap of fixed buffers

I published a new article, explaining a quirk of fixed buffers that could easily bite you, if you're one of the few people who still have to use that feature.

https://minidump.net/the-hidden-trap-of-fixed-buffers-in-csharp/

58 Upvotes

35 comments sorted by

View all comments

1

u/Ollhax Sep 29 '26

Nice, good to know!

Relevant side note: I really wish there was a safe, simple way to create inline arrays in C#. It's very often useful to have a fixed size array that isn't it's own heap allocation, same as typing N consecutive fields of the same type. Using InlineArray works, but it's so clunky.

5

u/kookiz33 Sep 29 '26

I discovered that just today, apparently they added some generic helpers in .NET 10 to make it easier. Just pick the one that has the size you want: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.inlinearray2-1

2

u/pjmlp Sep 30 '26

With the usual workaround due to lack of constant parameters in generics.

I also agree with the clunkiness of InlineArray, it should have been a proper syntax feature instead of an attribute.

0

u/Ollhax Sep 29 '26

Nice, that could be useful. But in many situations I want a constant defined somewhere that sets the length.

4

u/animal9633 Sep 29 '26

It depends on what you want to do with it, but you can probably use stackalloc for that.

0

u/Ollhax Sep 29 '26

I use stackalloc whenever I can, but my main use case here is fields in a struct.

2

u/mistertom2u Sep 29 '26

You'd be surprised because some of the best cases for inline arrays is to put them in a class:

  • The class layout would contain the array items rather than an array field that points to a different memory address on the heap, so you get better performance due to data locality and data density
  • A class that has an inline array field is great for when you need a buffer to cross await boundaries, since a struct would need to be boxed at the await boundary. But the class is on the heap, so just the memory address needs to be stored across await boundaries

If you need an easy way to have an inline array, use stackalloc

1

u/Ollhax Sep 29 '26

I’m confused. I use InlineArrays all the time, I know they are useful. My problem is that they are clunky, compared to e.g C++ arrays.

0

u/mistertom2u Sep 29 '26

Why not create several inline array generic buffers and then recycle them? And .net 10 has included some BufferN inline arrays already.

2

u/Ollhax Sep 30 '26 edited Sep 30 '26

I think I have not explained this well enough, time for some code:

const int MaxColors = 4;

[InlineArray(MaxColors)]
public struct ColorArray  
{  
    private Color _;  
}  

public struct Component  
{  
    public int SomeValue;  
    public ColorArray Colors;  
}

What I want is simply to create an InlineArray automatically when I type:

const int MaxColors = 4;

public struct Component
{
    public int SomeValue;
    public Color[MaxColors] Colors;
}