0

I've been trying to generate a alocation free from a struct in c#

Basically I create my on struct that recives an string (ReadOnlySpan) that could have any size like 'ABC1234.5GDS' and then inside of the constructor of that struct I create a Span stackalloc char[5] then I interate on ReadOnlySpan getting only the 5 first numbers at the end my Span has the '12345' on it but how do I pin that address to a char[] so I can use that later.

Basically I want to do the same as DateTime that you can be allocation free until you call ToString()

public readonly struct AllocFree
{
    private readonly char[] data;

    public AllocFree(ReadOnlySpan<char> input)
    {
        int position = 0;
        Span<char> newData = stackalloc char[5];

        for (int i = 0; i < input.Length; i++)
        {
            if (char.IsDigit(input[i]))
            {
                newData[position] = input[i];
                position++;
            }

            if (position == 4)
                break;
        }

        // How to make this a allocation free.
        data = newData;

        // This is a no allocation free.
        data = newData.ToArray();
    }
    public override string ToString() => new String(data);
}
  • 1
    Maybe if you resort to unsafe `private unsafe fixed` code. Otherwise you'll have to `char d1; char d2;...` – Jeremy Lakeman Jul 14 '22 at 02:12
  • You'll also want to implement `ISpanFormattable` so you don't create an extra allocation while building any interpolated strings. – Jeremy Lakeman Jul 14 '22 at 02:22
  • Doesn't seem to make sense to do this: either way you are going to have to create the string. the only way around it is to make a function which accepts a `Span` and use `String.Create` https://learn.microsoft.com/en-us/dotnet/api/system.string.create?view=net-6.0 or to use some kind of `StringBuilder` – Charlieface Jul 19 '22 at 13:46
  • For an example of `private unsafe fixed` see [C# array within a struct](https://stackoverflow.com/a/8704505) or [Is a Span pointing to Fixed Sized Buffers without a fixed expression possible?](https://stackoverflow.com/q/54285865/3744182). – dbc Jul 21 '22 at 05:03

0 Answers0