YAML
suggest changeYAML ("YAML Ain't Markup Language") is a human-friendly data serialization standard commonly used for configuration files, infrastructure-as-code manifests (Kubernetes, Docker Compose), and CI/CD pipelines.
In the .NET ecosystem, the de facto standard library for reading, writing, and manipulating YAML documents is YamlDotNet.
1. Installation
Install the YamlDotNet package via NuGet:
dotnet add package YamlDotNet
2. Deserializing YAML into Strongly Typed C# Objects
YamlDotNet uses IDeserializer built via DeserializerBuilder:
using System;
using System.Collections.Generic;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
// Define C# model matching YAML structure
public class ServerConfig
{
public string Host { get; set; } = string.Empty;
public int Port { get; set; }
public DatabaseSettings Database { get; set; } = new();
public List<string> AllowedOrigins { get; set; } = new();
}
public class DatabaseSettings
{
public string ConnectionString { get; set; } = string.Empty;
public int MaxConnections { get; set; }
}
class Program
{
static void Main()
{
string yamlContent = """
host: localhost
port: 5000
database:
connectionString: Server=sql.local;Database=app;
maxConnections: 50
allowedOrigins:
- http://localhost:3000
- https://myapp.com
""";
// Build deserializer with camelCase matching
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.IgnoreUnmatchedProperties()
.Build();
ServerConfig config = deserializer.Deserialize<ServerConfig>(yamlContent);
Console.WriteLine($"Server: {config.Host}:{config.Port}");
Console.WriteLine($"DB Connections: {config.Database.MaxConnections}");
Console.WriteLine($"Origins: {string.Join(", ", config.AllowedOrigins)}");
}
}
3. Serializing C# Objects to YAML
Use ISerializer built via SerializerBuilder:
using System;
using System.Collections.Generic;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
public class DeploymentManifest
{
[YamlMember(Alias = "apiVersion")]
public string ApiVersion { get; set; } = "apps/v1";
[YamlMember(Alias = "kind")]
public string Kind { get; set; } = "Deployment";
[YamlMember(Alias = "metadata")]
public Dictionary<string, string> Metadata { get; set; } = new()
{
{ "name", "order-service" },
{ "tier", "backend" }
};
[YamlMember(Alias = "replicas")]
public int Replicas { get; set; } = 3;
}
class SerializationExample
{
static void Main()
{
var manifest = new DeploymentManifest();
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
.Build();
string yamlOutput = serializer.Serialize(manifest);
Console.WriteLine(yamlOutput);
}
}
Generated output:
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
tier: backend
replicas: 3
4. Reading Untyped Dynamic YAML
When processing arbitrary or unknown YAML schemas, deserialize into dynamic dictionaries and lists:
using System;
using System.Collections.Generic;
using YamlDotNet.Serialization;
string dynamicYaml = """
app: Microservice
enabled: true
settings:
retryCount: 3
""";
var deserializer = new DeserializerBuilder().Build();
var root = (Dictionary<object, object>)deserializer.Deserialize(new System.IO.StringReader(dynamicYaml));
Console.WriteLine("App: " + root["app"]);
Console.WriteLine("Enabled: " + root["enabled"]);
var settings = (Dictionary<object, object>)root["settings"];
Console.WriteLine("Retry: " + settings["retryCount"]);
5. Custom Type Converters
To customize how a specific type is represented in YAML, implement IYamlTypeConverter:
using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using Version = System.Version; // YamlDotNet.Core also has a Version type
public class VersionYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(Version);
public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
var scalar = parser.Consume<Scalar>();
return Version.Parse(scalar.Value);
}
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
if (value is Version version)
{
emitter.Emit(new Scalar(version.ToString(3)));
}
}
}
// Register converter:
var serializer = new SerializerBuilder()
.WithTypeConverter(new VersionYamlConverter())
.Build();
6. Best Practices
- Validate Configuration: Combine YamlDotNet deserialization with
System.ComponentModel.DataAnnotations(e.g.[Required],[Range]) to validate loaded configurations immediately at application startup. - Ignore Unmatched Properties: In microservice environments, configure
.IgnoreUnmatchedProperties()on the deserializer to remain forward-compatible when configuration schemas add new optional keys. - Omit Default/Null Values: Use
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitDefaults | DefaultValuesHandling.OmitNull)to keep generated configuration files concise and readable.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents