Recursive AI

Ignore a property during YAML serialization in C#

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

Use [YamlIgnore] to keep a runtime-only property out of YAML even when it has a value.

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10 (example).

C#
using OneYaml;
 
var job = new Job("nightly", 7);
var yaml = YamlSerializer.Serialize(job);
Console.Write(yaml);
 
record Job(string Name,
    [property: YamlIgnore] int RunCount);

Unzip the example, then dotnet run.

The snippet prints:

Text
name: nightly

The run count is 7 in memory but has no key in the output.

Variations

Read a file that still includes the old key. Keep the Job record and replace the code above it (after using OneYaml;):

C#
var job = YamlSerializer.Deserialize<Job>(
    "name: nightly\nrunCount: 7\n")!;
Console.WriteLine(job.RunCount);
Text
0

The short answer

Mark the property with [YamlIgnore] from the OneYaml namespace. With no condition, the property is neither read from YAML nor written to it. Use it for a value the app fills in at runtime, such as a count of runs since the job was loaded. It doesn’t remove the property from the object or clear its value in memory.

To omit a property only when it’s null, use YamlIgnore(Condition = YamlIgnoreCondition.WhenWritingNull); it still reads the property from YAML.

How do I exclude just one property from YAML serialization?

Put the attribute above the property you want to exclude. If it’s a positional record, write [property: YamlIgnore] on that parameter so the attribute lands on the generated property. The other property in the example, Name, still gets written as name under OneYaml’s default naming policy. You don’t need a custom converter or a setting that also changes other members.

The attribute changes the serializer’s contract for that model, not the source text of a YAML file. Serializing a Job gives you fresh YAML without runCount. To remove a key from an existing YAML file without regenerating the rest, use a patch against a YamlDocument instead.

Does an ignore attribute also apply when deserializing YAML?

Yes. The variation supplies runCount: 7 and reads back 0, the default for the ignored int in this record. It doesn’t restore a saved count. Initialize runtime state in the application after it loads the config. If you still need to accept a property from YAML, unconditional ignore is not the right choice.

OneYaml honors System.Text.Json.Serialization.JsonIgnore when there is no corresponding YAML attribute; when both are present, the YAML attribute takes precedence for OneYaml. The serializer’s attribute table shows which attributes are shared. Decide whether the member belongs in YAML and JSON separately if you use the same model for both.

All oneyaml C# recipes