Custom parsers

Register a field parser when conversion differs by column, or a runtime parser when the same type should be parsed consistently across fields. Both are data-reader conversion settings; SpanObjectBuilder.SetParser configures the separate constructor-mapping path.

Built-in parsers

The data reader registers these types automatically. Declare a column with WithField<T>() or WithField<T>("name") and read it with GetFieldValue<T>().

Group Types
Text string, char
Boolean and identifier bool, Guid
Integers byte, short, int, long
Other numbers decimal, float, double
Dates and times DateTime, DateTimeOffset, DateOnly, TimeOnly

The default numeric and temporal parsers use invariant culture. A field’s configured format or parser can control how that field is read.

Opt-in parsers

Registration inside WithParsers(...) Package Types
p => p.UseNetworkValues() PocketCsvReader IPAddress, IPNetwork, PhysicalAddress
p => p.UseChrononuensis() PocketCsvReader.Chrononuensis MonthDay, YearDay, YearWeek, YearMonth, YearQuarter, YearSemester, Year, Olympiad, Decade, Century
p => p.UseNetTopologySuite() PocketCsvReader.NetTopologySuite Geometry, Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection

For types without a registration helper, use WithParsers(p => p.WithParser(...)) to register a delegate for the reader. Use WithField<T>(f => f.WithParser(...)) when parsing rules apply to a single column.

Example type Delegate input Delegate
TimeSpan ReadOnlySpan<char> (ReadOnlySpan<char> text) => TimeSpan.Parse(text, CultureInfo.InvariantCulture)
Version ReadOnlySpan<char> (ReadOnlySpan<char> text) => Version.Parse(text)
IPEndPoint ReadOnlySpan<char> (ReadOnlySpan<char> text) => IPEndPoint.Parse(text)
Uri string (string text) => new Uri(text, UriKind.Absolute)
MailAddress string (string text) => new MailAddress(text)

Complete custom type example

using System.Globalization;
using System.Text;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithoutHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Indexed().WithField<Coordinate>())
    .WithParsers(p => p.WithParser((ReadOnlySpan<char> text) =>
    {
        var separator = text.IndexOf(';');
        if (separator < 0) throw new FormatException("Expected x;y");
        return new Coordinate(
            int.Parse(text[..separator], CultureInfo.InvariantCulture),
            int.Parse(text[(separator + 1)..], CultureInfo.InvariantCulture));
    }))
    .Build();
using var stream = new MemoryStream(Encoding.UTF8.GetBytes("3;4\n"));
using var reader = csv.ToDataReader(stream);
while (reader.Read())
{
    var point = reader.GetFieldValue<Coordinate>(0);
    Console.WriteLine($"({point.X}, {point.Y})");
}
public record Coordinate(int X, int Y);
(3, 4)

Parser scope and precedence

Scope API Effect
Explicit getter GetFieldValue<T>(ordinal, parser) Parser for that requested read
Field WithField<T>(f => f.WithParser(...)) Parser for one schema field
Field format Specialized schema field builder Formatted conversion, ahead of runtime type defaults
Runtime type WithParsers(p => p.WithParser(...)) Shared type parser when no field override wins
Opt-in defaults UseNetworkValues(), UseChrononuensis(), UseNetTopologySuite() Fallback registrations; explicit runtime parsers win in either registration order

The latest explicit registration for the same field/type replaces its previous parser. Schema builders can supply default numeric/temporal formats; use a field parser to override that field’s format deliberately. Preserve underlying parse exceptions rather than silently substituting zero or an empty value.

Sparse indexes also use the reader’s registered runtime parser for a key without an explicit format or culture. Use the reader’s runtime parser with a sparse index

UTF-8 parsers

Use WithUtf8Parser<T>(utf8Parser, fallback) inside WithParsers(...) to supply a typed byte parser and an equivalent character parser. Here a CSV column uses on and off for Boolean values.

using PocketCsvReader;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithoutHeader())
    .WithStreamInitialization(StreamInitializationOptions.Utf8)
    .WithParsers(p => p.WithUtf8Parser<bool>(TryParseSwitch, ParseSwitch))
    .Build();

using var stream = new MemoryStream("on,off"u8.ToArray());
using var reader = csv.ToDataReader(stream);
if (reader.Read())
    Console.WriteLine($"{reader.GetBoolean(0)} {reader.GetBoolean(1)}");

static bool TryParseSwitch(ReadOnlySpan<byte> text, out bool value)
{
    value = text.SequenceEqual("on"u8);
    return value || text.SequenceEqual("off"u8);
}

static bool ParseSwitch(ReadOnlySpan<char> text)
{
    if (text.SequenceEqual("on")) return true;
    if (text.SequenceEqual("off")) return false;
    throw new FormatException("Expected on or off.");
}
True False

A byte parser returns true only for a complete field match. It receives borrowed, valid UTF-8 for the duration of the call. The fallback runs when the byte parser returns false or the reader needs its character path, such as on TextReader input or for an escaped field. Schema parsers and formats, sequence substitutions, and row filters continue through their existing paths.

An explicit runtime parser takes precedence over a built-in for the same type. Registrations for other types leave eligible built-ins available. Native UTF-8 mode enables the built-ins automatically. See UTF-8 input for the built-in types and UseIsoDateAsDateTime().

Parsing spans without intermediate strings

ParseSpan<T> consumes ReadOnlySpan<char> synchronously. Select the overload using an explicitly typed span lambda or a ParseSpan<T> variable. For an overloaded method group, assign it to that delegate first. With C# 13+, overload priorities retain legacy string behavior for untyped lambdas; on older compilers, type the parameter explicitly when ambiguous.

String delegates remain supported but require a string input. Typed span reads avoid that intermediate string, although returned objects and boxed value reads can allocate. Do not retain the supplied span. See buffer ownership.

Nullable/reference typed reads skip custom parsers for null fields according to the getter’s null policy. Array getters use registered element parsers unless a whole-array parser wins. Native JSON decoding and CSV sanitization are format-specific; see value handling.

For direct use of the public SpanParser, TryParse returns false for supported conversion failures; configuration errors and unexpected failures are not a general-purpose exception suppression contract. The cell-level API is IsValid.

The Chrononuensis integration supplies temporal period parsers. Reproducible parser benchmarks are linked from benchmark guidance.

Built-in duration and version parsing

A column declared with WithField<TimeSpan>("ts") uses .NET’s invariant-culture TimeSpan parser directly on the field span. For example, 01:30:00 represents 90 minutes. GetValue("ts") returns a boxed TimeSpan for valid input and throws for malformed input. Earlier versions returned the field text.

A column declared with WithField<Version>("version") uses .NET’s System.Version parser directly on the field span. The format is major.minor[.build[.revision]]. Values such as 1.2.3 are accepted. Prerelease suffixes such as 1.2.3-beta require a custom parser.

URI values

Call .WithParsers(p => p.UseUriValues()) to read a column declared with WithField<Uri>("url") as an absolute URI. Pass UriKind.Relative or UriKind.RelativeOrAbsolute to accept relative references. Explicit field and runtime parsers take precedence. PocketCsvReader converts the decoded field span to a string at the System.Uri constructor boundary.

Network values

Enable UseNetworkValues() to read IP addresses (IPAddress), IP endpoints (IPEndPoint), CIDR networks (IPNetwork), and MAC addresses (PhysicalAddress) with the core package. For endpoints with a port, use forms such as 192.0.2.10:443 or [2001:db8::1]:443. The .NET parsers receive the decoded field span directly. Explicit field and runtime parsers take precedence over these defaults.

using System.Net;
using System.Net.NetworkInformation;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithoutHeader().WithLineTerminator("\n"))
    .WithSchema(s => s.Indexed()
        .WithField<IPAddress>()
        .WithField<IPNetwork>()
        .WithField<PhysicalAddress>())
    .WithParsers(p => p.UseNetworkValues())
    .Build();

using var stream = new MemoryStream("2001:db8::1,192.0.2.0/24,00:1A:2B:3C:4D:5E\n"u8.ToArray());
using var reader = csv.ToDataReader(stream);
if (reader.Read())
{
    var address = reader.GetFieldValue<IPAddress>(0);
    var network = reader.GetFieldValue<IPNetwork>(1);
    var mac = reader.GetFieldValue<PhysicalAddress>(2);
}

Schemas, formats, and cultures
Null, empty, and missing values