I'm writing a high-performance parser for a comma delimited stream (network). My goal is to parse and convert directly from binary to dotnet primitives. Based on my testing thus far, Span performance is incredible, but the type is difficult to work with due to restrictions inherent to ref structs. I've hit a roadblock trying to find an efficient way to store Span constants (comma, newline, etc.) used throughout my application. The only solution that seems to exist to store them as byte and convert them in the class bodies of methods...or hardcode Span<byte> delimiter = Encoding.UTF8.GetBytes("\r\n") in every method body.
The following is what I'd like to achieve but it gives the error - `CS8345 Field or auto-implemented property cannot be of type 'Span' unless it is an instance member of a ref struct.
public class Parser
{
Span<byte> NewLine = new byte[]{ (byte)'\n' };
}
There's got to be a better way! Please help!
You can create
ReadOnlySpan<byte>with UTF-8 literal in .NET 7:Or use
Memory/ReadOnlyMemory:And usage:
Or decorate aforementioned approach into method/expression bodied property:
Demo