Search code examples
c#pointerssizeoffixedunsafe

How to get fixed buffer length?


Is there a way to get the length of a fixed size buffer?

Something like:

public struct MyStruct
{
    public unsafe fixed byte buffer[100];

    public int foo()
    {
        return sizeof(buffer); // Compile error.
    }
}

Is there any way to accomplish something like this?


Solution

  • Well like in C++, you have to keep size of built-in arrays. Same applies for fixed buffers in C#. This type is comparable to inline_array. This gives you benefits such as static code checking. They are a bit of a pain to work with as they aren't C#'s first class feature. So probably the best solution is to keep size as a part of struct. You will probably just have to deal with it or use a collection/C#'s System.Array. Maybe another solution would be to create fixed buffer as a seperate struct and then make it part of another stucts with other data.