Recursive AI

Inspect YAML token types in a C# custom converter

OneYaml is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Check reader.TokenType before advancing the reader. It’s already on the first token of the value.

Terminal
dotnet add package OneYaml

The library targets .NET 8 and later; the example project uses .NET 10.

C#
using OneYaml;
 
sealed class PortReader
    : YamlConverter<Port>
{
    public override Port Read(
        ref Utf8YamlReader reader,
        Type type,
        YamlSerializerOptions options)
    {
        var kind = reader.TokenType;
        Console.WriteLine(kind);
        if (kind != YamlTokenKind.Scalar)
            throw reader.CreateException(
                "Expected a port number.");
 
        return new Port(reader.GetInt32());
    }
 
    public override void Write(
        Utf8YamlEmitter writer, Port value,
        YamlSerializerOptions options) =>
        writer.WriteNumberValue(
            value.Number);
}
 
[YamlConverter(typeof(PortReader))]
record Port(int Number);
 
static class Program
{
    static void Main()
    {
        var port = YamlSerializer
            .Deserialize<Port>("8080")!;
        Console.WriteLine(port.Number);
    }
}

Paste the code above into Program.cs of a new dotnet new console project and dotnet run, or unzip the example and dotnet run.

Prints:

Text
Scalar
8080

If the input isn’t a scalar, CreateException makes a binding error with the location of the current token.

Variations

To see the opening token of a sequence, replace the Deserialize call and the line that prints port.Number with:

C#
try
{
    YamlSerializer.Deserialize<Port>("[8080, 8081]");
}
catch (YamlException error)
{
    Console.WriteLine(error.Category);
}

Prints SequenceStart and then the YamlException error category, Binding. This converter accepts only one port, not a list.

The short answer

Inspect reader.TokenType as soon as YamlConverter<T>.Read is called. The reader is already on the first token of the value, so don’t call Read() first just to find its kind. Use Scalar for a single value, MappingStart for key-value pairs, and SequenceStart for a list. The port converter accepts only a scalar and calls GetInt32() to read it.

How do I tell whether a YAML value is a scalar, mapping, or sequence in C#?

Use the token kind to choose how to read the value. Scalar describes the shape, not the C# type: 8080 and web can both arrive as scalars. GetInt32() checks whether the scalar can be read as a 32-bit integer; use GetString() if you need the scalar’s text instead. For a shape your converter doesn’t accept, use reader.CreateException(...) rather than returning a default value. The error can then point to the token the caller needs to fix.

The converter also doesn’t need to handle a separate alias token. OneYaml follows YAML aliases before giving you the value, so you inspect the referenced value’s shape. TokenType doesn’t tell you how that value was spelled. If you need the YAML tag instead, TryGetTag gives the resolved tag and TryGetRawTag gives the text as written.

How far should a custom YAML converter advance the reader?

Leave it on the last token of the value you were asked to read. For a scalar, that’s the very token you started on. For a collection, advance through the contents and stop on the matching MappingEnd or SequenceEnd, not the token after it. If you’re inside a mapping and decide to ignore a value, use Skip() at the value to skip a whole nested collection. Then continue with the next key. See the reader guide for a complete mapping converter.

The reader exists only during the converter call; it’s not a public file tokenizer you can construct separately. If your task is to inspect arbitrary documents, use YamlDocument to walk the structure instead of registering a converter for every type you might find.

All oneyaml C# recipes