Set EnumNamingPolicy for the default spelling and use [YamlEnumMemberName] to override one value.
dotnet add package OneYamlTargets .NET 8 and .NET 10 (used in the download).
using System; using System.Text.Json; using OneYaml; var options = new YamlSerializerOptions { EnumNamingPolicy = JsonNamingPolicy.KebabCaseLower, }; Console.Write(YamlSerializer.Serialize( new Job(Mode.DryRun), options)); Console.WriteLine("---"); Console.Write(YamlSerializer.Serialize( new Job(Mode.ApplyChanges), options)); record Job(Mode Mode); enum Mode { DryRun, [YamlEnumMemberName("apply")] ApplyChanges, }
Unzip the example, then dotnet run.
dotnet run prints:
mode: dry-run --- mode: apply
The first document uses the naming policy. The second uses the explicit name apply. If an input string doesn’t name a member, OneYaml throws YamlException.
Variations
Read the names back. Replace the three Console calls with this loop. It reads the attribute name in uppercase and a declared C# name:
foreach (string yaml in new[] { "mode: APPLY", "mode: DryRun" }) { var job = YamlSerializer .Deserialize<Job>(yaml, options)!; Console.WriteLine(job.Mode); }
ApplyChanges DryRun
Related recipes
The short answer
OneYaml writes enum values by name by default. Set YamlSerializerOptions.EnumNamingPolicy if you want those names in a consistent format such as dry-run. Put [YamlEnumMemberName("apply")] on one member to set its exact YAML spelling instead of using the policy. The two controls work together: the policy names ordinary members, and the attribute names exceptions.
How do I give a C# enum a custom YAML string value?
Apply the attribute to the enum member, not to the property holding it. The ApplyChanges member still has its ordinary C# name, but when you serialize it OneYaml writes apply. Keep the attribute spelling unchanged so the name written in the YAML file stays apply even if you rename the C# member. A policy-only name, such as dry-run from DryRun, can change when the C# name does.
PropertyNamingPolicy names the keys in a mapping, such as Mode → mode. It does not name the enum values after the colon. The enum guide documents that distinction. If a YAML consumer wants lower-kebab-case values, set EnumNamingPolicy explicitly instead of relying on your property naming option.
How do I read YAML enum names back into C#?
Pass the same options to Deserialize when reading files you wrote with that naming policy. As shown above, OneYaml also reads the declared member name DryRun and the attributed name APPLY regardless of letter case. That tolerance is about reading: the writer still emits the single configured spelling for each member. It doesn’t turn an unrelated string like preview into a default enum member.