Use [YamlRequired] when a config file must supply a value even if the C# property has a default.
dotnet add package OneYamlTargets .NET 8 and .NET 10 (used in the download).
using System; using OneYaml; try { YamlSerializer.Deserialize<Server>( "host: api\n"); } catch (YamlException error) { Console.WriteLine(error.Message); } class Server { public string Host { get; set; } = ""; [YamlRequired] public int Port { get; set; } = 80; }
Unzip the example, then dotnet run.
dotnet run prints:
The required key 'port' is missing. (line 1, column 1)Host is supplied by the inline YAML. OneYaml throws YamlException for the missing port key instead of returning a server with Port set to 80.
Variations
Require the key, but allow an explicit null. Change Port to public int? Port { get; set; } = 80;, keeping [YamlRequired]. Replace the contents of the try block with:
var server = YamlSerializer .Deserialize<Server>( "host: api\nport: null\n")!; Console.WriteLine( server.Port?.ToString() ?? "null");
nullRelated recipes
The short answer
Mark the C# property with [YamlRequired] in the OneYaml namespace. YamlSerializer.Deserialize<T> then requires the matching key in the YAML mapping. In this recipe Port maps to port. Even though the property has an initializer, the binder throws a YamlException if port is absent. No serializer option is needed to turn on this check.
How do I handle missing required properties when deserializing YAML?
Use required members for settings that have no safe default for the caller. Leave the optional members unmarked, with defaults only where they make sense. OneYaml’s attribute table also lists the C# required keyword and [JsonRequired] from System.Text.Json.Serialization. Use the keyword when C# callers should also be required to initialize the member; use the YAML attribute when you want to impose the presence check on YAML without changing how C# callers create the object. If you already share a model with JSON, OneYaml honors [JsonRequired] when there isn’t a YAML attribute on the member.
A missing key has no token to underline. In the example the error names port and points to the start of the mapping at line 1, column 1. If users spell port as prot, required binding still sees port as missing. To point the error at the misspelling instead, set UnmappedMemberHandling = YamlUnmappedMemberHandling.Disallow.
Does a required YAML property have to be non-null?
Presence and value are different checks. In the variation, port: null supplies the key, and int? lets the property hold null. Removing port entirely still fails. If your config distinguishes “not specified” from “explicitly unset,” make the member required and nullable. If the setting must be an integer, keep int as in the first example. Rules such as “the port must be between 1 and 65535” belong in application validation after deserialization; [YamlRequired] checks for the key, not whether the value makes sense for your app.