Recursive AI

Deserialize polymorphic YAML in C#

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

A type discriminator is a YAML key that selects the C# type for each item.

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10 (used in the download).

C#
using System;
using OneYaml;
 
var shapes =
    YamlSerializer.Deserialize<Shape[]>("""
    - $type: circle
      radius: 2
    - $type: square
      side: 3
    """)!;
 
foreach (var shape in shapes)
    Console.WriteLine(shape.GetType().Name);
 
[YamlPolymorphic]
[YamlDerivedType(typeof(Circle), "circle")]
[YamlDerivedType(typeof(Square), "square")]
abstract record Shape;
record Circle(double Radius) : Shape;
record Square(double Side) : Shape;

Unzip the example, then dotnet run.

The two entries bind as Circle and Square.

Text
Circle
Square

The full program

The download also tries triangle, which isn’t registered. An unknown discriminator throws YamlException with the key’s location and path.

C#
using System;
using OneYaml;
 
var shapes =
    YamlSerializer.Deserialize<Shape[]>("""
    - $type: circle
      radius: 2
    - $type: square
      side: 3
    """)!;
 
foreach (var shape in shapes)
    Console.WriteLine(shape.GetType().Name);
 
var unknown = "- $type: triangle";
try
{
    YamlSerializer.Deserialize<Shape[]>(unknown);
}
catch (YamlException error)
{
    Console.WriteLine(error.Message);
}
 
[YamlPolymorphic]
[YamlDerivedType(typeof(Circle), "circle")]
[YamlDerivedType(typeof(Square), "square")]
abstract record Shape;
record Circle(double Radius) : Shape;
record Square(double Side) : Shape;

dotnet run prints:

Text
Circle
Square
'triangle' is not a known value of '$type' for Shape. (line 1, column 10, path /0/$type)

Variations

Use kind instead of $type. If your YAML already uses kind, replace [YamlPolymorphic] in the snippet at the top with this attribute. Keep both [YamlDerivedType] registrations.

C#
[YamlPolymorphic(TypeDiscriminatorPropertyName = "kind")]

Replace the inline YAML with:

YAML
- kind: circle
  radius: 2
- kind: square
  side: 3

It still prints:

Text
Circle
Square

The short answer

Deserialize the YAML sequence as Shape[]. Mark Shape with [YamlPolymorphic] and register each supported record with [YamlDerivedType]. Put $type on each item: circle selects Circle, and square selects Square. The key selects a registered type, not an arbitrary .NET type name.

How do I use a type discriminator in YAML?

The declared element type stays Shape, so one array can hold both shapes. Each input item is a YAML mapping, a set of keys and values. OneYaml reads $type to find the derived type, then binds the other keys to that type. In the example, radius belongs to Circle and side belongs to Square; neither is a member of the base record.

If you control the YAML, put the discriminator first. OneYaml can find it later in the mapping too, but the serializer guide notes that this lookahead counts against the alias budget, the limit on how much data YAML references can expand into. If you already have files that use a key such as kind, set TypeDiscriminatorPropertyName on [YamlPolymorphic] and make the files use the same key. The values are still the names on the derived type attributes.

Why does deserialization reject an unknown type discriminator?

Check the input value against the names on the attributes, not against the C# class names. In the full program’s output, /0/$type points to the first element’s discriminator. Either correct that value in the file or explicitly register a type that your application knows how to handle. Changing the file to use a .NET type name does not register it.

A missing discriminator is different from an unknown one. The attribute reference says OneYaml can read the base type itself when no discriminator is present and the base type can be created. Here Shape is abstract, so both items need a discriminator. When writing YAML back, keep the declared type as Shape or a collection of Shape; serializing a concrete shape as its own type doesn’t write the base type’s discriminator.

All oneyaml C# recipes