---
title: "Deserialize polymorphic YAML in C#"
url: https://recursiveai.org/oneyaml/csharp/cookbook/deserialize-polymorphic-yaml/
description: "Use a type discriminator to read a mixed YAML list into registered C# types. See what OneYaml does when a discriminator value isn’t recognized."
version: "1.2.1"
---

# 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.

[NuGet](https://www.nuget.org/packages/OneYaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-csharp) · [Docs](https://recursiveai.org/oneyaml/csharp/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/csharp/cookbook/deserialize-polymorphic-yaml/deserialize-polymorphic-yaml.zip)

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

```shell
dotnet add package OneYaml
```

Targets .NET 8 and [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (used in the download).

```csharp
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](https://recursiveai.org/oneyaml/csharp/cookbook/deserialize-polymorphic-yaml/deserialize-polymorphic-yaml.zip), 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.

```csharp
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.

```csharp
[YamlPolymorphic(TypeDiscriminatorPropertyName = "kind")]
```

Replace the inline YAML with:

```yaml
- kind: circle
  radius: 2
- kind: square
  side: 3
```

It still prints:

```text
Circle
Square
```


## Related recipes

- [Parse YAML into C# classes](https://recursiveai.org/oneyaml/csharp/cookbook/parse-yaml-into-classes/)
- [Report YAML errors with a line and column](https://recursiveai.org/oneyaml/csharp/cookbook/errors-with-line-and-column/)

## 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](https://github.com/recursive-ai-oss/oneyaml-csharp/blob/7818048c4be434333767c47d66176fc626d1da8e/docs/serializer.md#L202-L204) 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](https://github.com/recursive-ai-oss/oneyaml-csharp/blob/7818048c4be434333767c47d66176fc626d1da8e/src/OneYaml/Serialization/YamlPolymorphism.cs#L83-L86) 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.
