C# MessagePack
last modified November 15, 2026
This article shows how to serialize objects in C# with MessagePack. We cover attributes and numeric keys, contractless mode, ignored members, LZ4 compression, source generation, and schema evolution.
MessagePack is a binary serialization format. A value is encoded as a type marker followed by its payload: small integers fit in a single byte, short strings carry their length in the marker, and arrays and maps declare their element count up front. The format is defined by a public specification and implemented for many languages, so a C# service can exchange messages with a Go, Java, or Python service.
MessagePack-CSharp is the .NET implementation. It maps objects to
MessagePack arrays or maps, supports compression, and can generate formatters
at build time instead of using reflection. The examples use MessagePack
3.1.12, which is MIT-licensed; add it with
dotnet add package MessagePack. The namespace is
MessagePack.
Serializing an object
The standard contract marks a class with [MessagePackObject]
and gives every serialized member a numeric key with
[Key(n)]. The keys define the wire order; property names are not
transmitted.
using MessagePack;
using System.Text.Json;
var person = new Person { Id = 1, Name = "Alice", Email = "alice@example.com" };
byte[] packed = MessagePackSerializer.Serialize(person);
byte[] json = JsonSerializer.SerializeToUtf8Bytes(person);
Person copy = MessagePackSerializer.Deserialize<Person>(packed);
Console.WriteLine(Convert.ToHexString(packed));
Console.WriteLine($"MessagePack: {packed.Length} bytes");
Console.WriteLine($"JSON: {json.Length} bytes");
Console.WriteLine($"{copy.Id} {copy.Name} {copy.Email}");
Console.WriteLine(MessagePackSerializer.ConvertToJson(packed));
[MessagePackObject]
public class Person
{
[Key(0)] public int Id { get; set; }
[Key(1)] public string Name { get; set; } = "";
[Key(2)] public string Email { get; set; } = "";
}
The payload starts with 93, the marker for an array of three
elements. The identifier is the single byte 01, while each
string is prefixed with its length: A5 for the five characters
of Alice and B1 for the seventeen characters of the
email address. The total is 26 bytes against 51 bytes for the same object in
JSON.
[MessagePackObject]
public class Person
{
[Key(0)] public int Id { get; set; }
...
}
The numeric keys are the schema. They are written to the payload instead of
the property names, which is where most of the saving comes from. Keys must
be unique and should never be reused for a different meaning. The serializer
requires a public parameterless constructor or a constructor annotated with
[SerializationConstructor], and it serializes public members
that carry a [Key].
ConvertToJson decodes a MessagePack payload into JSON text for
debugging. It is a diagnostic tool, not a conversion path for production:
the JSON form is larger and loses the distinction between some binary and
string values.
$ dotnet run 9301A5416C696365B1616C696365406578616D706C652E636F6D MessagePack: 26 bytes JSON: 51 bytes 1 Alice alice@example.com [1,"Alice","alice@example.com"]
Contractless serialization
Not every type can be annotated, and not every team wants attributes on its
models. The contractless resolver maps public properties by name, without
[MessagePackObject] or [Key]. The trade-off is
that the names travel in the payload.
using MessagePack;
using MessagePack.Resolvers;
using System.Text.Json;
var person = new Person { Id = 1, Name = "Alice", Email = "alice@example.com" };
var options = MessagePackSerializerOptions.Standard
.WithResolver(ContractlessStandardResolver.Instance);
byte[] packed = MessagePackSerializer.Serialize(person, options);
byte[] json = JsonSerializer.SerializeToUtf8Bytes(person);
Person copy = MessagePackSerializer.Deserialize<Person>(packed, options);
Console.WriteLine(Convert.ToHexString(packed));
Console.WriteLine($"MessagePack: {packed.Length} bytes");
Console.WriteLine($"JSON: {json.Length} bytes");
Console.WriteLine($"{copy.Id} {copy.Name} {copy.Email}");
Console.WriteLine(MessagePackSerializer.ConvertToJson(packed));
public class Person
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
The payload now starts with 83, a map with three entries, and
each entry stores the property name before its value. The result is 40 bytes
instead of 26, still smaller than the 51-byte JSON document but no longer by
a wide margin.
var options = MessagePackSerializerOptions.Standard
.WithResolver(ContractlessStandardResolver.Instance);
The resolver is part of the serializer options and must be supplied to both
Serialize and Deserialize. Contractless mode is
convenient for existing DTOs, but it couples the wire format to property
names: renaming a property breaks compatibility with older payloads. The
attributed form uses stable numbers and is the better choice for a format
that outlives a refactoring.
$ dotnet run
83A2496401A44E616D65A5416C696365A5456D61696CB1616C696365406578616D706C652E636F6D
MessagePack: 40 bytes
JSON: 51 bytes
1 Alice alice@example.com
{"Id":1,"Name":"Alice","Email":"alice@example.com"}
Ignoring members and untrusted data
A serialized object often contains fields that must not leave the process,
such as a password hash or an internal flag. [IgnoreMember]
removes a member from the contract, even when the class has a
[Key] for it. The deserializer also needs a policy for input
that may be hostile.
using MessagePack;
var account = new Account { Id = 1, Name = "Alice", PasswordHash = "secret" };
byte[] packed = MessagePackSerializer.Serialize(account);
Console.WriteLine(Convert.ToHexString(packed));
Console.WriteLine(MessagePackSerializer.ConvertToJson(packed));
var options = MessagePackSerializerOptions.Standard
.WithSecurity(MessagePackSecurity.UntrustedData);
Account copy = MessagePackSerializer.Deserialize<Account>(packed, options);
Console.WriteLine($"{copy.Id} {copy.Name} [{copy.PasswordHash ?? "null"}]");
[MessagePackObject]
public class Account
{
[Key(0)] public int Id { get; set; }
[Key(1)] public string Name { get; set; } = "";
[IgnoreMember] public string? PasswordHash { get; set; }
}
The payload contains only the identifier and the name; the password hash is
absent and is null after the round trip. The JSON view confirms
that the secret never entered the byte array.
[IgnoreMember] public string? PasswordHash { get; set; }
[IgnoreMember] is checked at serialization time, so a member can
remain in the class for business logic without being exposed on the wire.
The attribute is stronger than a null check: a serializer configuration that
later enables non-public members still skips the ignored one.
MessagePackSecurity.UntrustedData enables protections for input
from an untrusted source: it resists hash collision attacks, limits the
object graph depth, and caps the decompressed size of a payload at 64 MB.
Those limits are not a substitute for validating the content. Never
deserialize data from an untrusted party into a type that can execute code
during construction, and keep the default depth limits unless a legitimate
message needs more.
$ dotnet run 9201A5416C696365 [1,"Alice"] 1 Alice [null]
Compression
MessagePack already removes the repeated property names that JSON carries, but it does not remove repetition inside the values. For larger messages, the serializer can compress the payload with LZ4, a fast compression algorithm designed for low latency.
using MessagePack;
var people = Enumerable.Range(1, 200)
.Select(i => new Person { Id = i, Name = $"User {i}", Email = $"user{i}@example.com" })
.ToList();
byte[] plain = MessagePackSerializer.Serialize(people);
var lz4Options = MessagePackSerializerOptions.Standard
.WithCompression(MessagePackCompression.Lz4BlockArray);
byte[] compressed = MessagePackSerializer.Serialize(people, lz4Options);
var restored = MessagePackSerializer.Deserialize<List<Person>>(compressed, lz4Options);
Console.WriteLine($"plain: {plain.Length} bytes");
Console.WriteLine($"compressed: {compressed.Length} bytes");
Console.WriteLine($"restored: {restored.Count} {restored[^1].Name}");
[MessagePackObject]
public class Person
{
[Key(0)] public int Id { get; set; }
[Key(1)] public string Name { get; set; } = "";
[Key(2)] public string Email { get; set; } = "";
}
Two hundred records take 6060 bytes without compression and 2336 bytes with
Lz4BlockArray, a reduction of about sixty percent. The
decompressed result contains the same two hundred objects, including the
last name.
var lz4Options = MessagePackSerializerOptions.Standard
.WithCompression(MessagePackCompression.Lz4BlockArray);
Compression is a property of the message, not of the type, so the reader must
use the same setting. Lz4BlockArray compresses the message in
blocks and is the mode intended for general use. Compression has a fixed
header and a per-block cost, which makes small messages larger; measure
before enabling it for every payload. The untrusted-data security setting
also enforces a maximum decompressed size, which is important precisely
because a small compressed payload can expand a great deal.
$ dotnet run plain: 6060 bytes compressed: 2336 bytes restored: 200 User 200
Source generation
The default serializer builds formatters with reflection on first use.
MessagePack 3 can generate the same formatters as C# source at build time.
The entry point is a partial class marked with
[GeneratedMessagePackResolver]; the generator fills in the
resolver and a formatter for every [MessagePackObject] type it
finds.
using MessagePack;
using MessagePack.Resolvers;
var person = new Person { Id = 1, Name = "Alice" };
var options = MessagePackSerializerOptions.Standard.WithResolver(
CompositeResolver.Create(AppResolver.Instance, BuiltinResolver.Instance));
byte[] packed = MessagePackSerializer.Serialize(person, options);
Person copy = MessagePackSerializer.Deserialize<Person>(packed, options);
Console.WriteLine(Convert.ToHexString(packed));
Console.WriteLine($"{copy.Id} {copy.Name}");
[MessagePackObject]
public class Person
{
[Key(0)] public int Id { get; set; }
[Key(1)] public string Name { get; set; } = "";
}
[GeneratedMessagePackResolver]
public partial class AppResolver
{
}
The byte array is the same one produced by the reflection-based serializer
for the same two properties. The generated resolver supplies the formatter
for Person, and the built-in resolver supplies formatters for
int and string.
[GeneratedMessagePackResolver]
public partial class AppResolver
{
}
The generator runs during compilation, so the resolver and its formatters
are ordinary types in the assembly. That removes the reflection cost at
startup and makes the formatters visible in the build output, where they can
be read and stepped through. CompositeResolver tries each
resolver in order: the generated one handles the application types, and the
built-in one handles primitives and strings. Collections and other framework
types need a formatter for their element type plus a resolver that can build
the collection formatter.
Source generation is the supported route for Native AOT and for trimmed applications, where reflection-based member discovery may be removed by the linker. It also helps services that need a predictable startup time. The project can keep using the default reflection-based path during development and switch the options to the generated resolver in the published build.
$ dotnet run 9201A5416C696365 1 Alice
Schema evolution
The numeric keys make a MessagePack contract tolerant of some changes. A writer that adds a new member at the end produces a longer array; an older reader expects fewer elements and ignores the extra ones. In the other direction, an older writer produces a shorter array, and a newer reader leaves the missing members at their default values.
That compatibility depends on never renumbering an existing key, never changing its type, and never assigning a retired key to a different member. Keys are permanent identifiers, not positions in the class. When a member is removed, its key should stay reserved. If the payload is a map rather than an array, for example because contractless mode was used, renaming a property is a breaking change because the name itself is the key.
Limitations
MessagePack is not human-readable, and that is the point: inspecting a
payload requires a decoder such as ConvertToJson or a dedicated
tool. Public HTTP APIs usually prefer JSON, where clients can read responses
and debug requests with ordinary tools. MessagePack fits internal service
calls, caches, queues, and storage where both ends control the schema and
the volume justifies the smaller payload.
The serializer is also not a validator. Unknown keys are skipped, missing keys become defaults, and a payload can describe an object that the application would never create itself. Treat deserialized input as untrusted, validate the resulting object, and keep the security options for untrusted data. For long-term storage, record the schema version alongside the payload so that a future reader knows which keys are expected.
The JSON and Newtonsoft Json.NET tutorials cover the text-based alternatives. The byte array to hex string tutorial explains the hex output used in the examples.
Source
In this article we have serialized objects in C# with MessagePack. See also the JSON, Newtonsoft Json.NET, and byte array to hex string tutorials.
Author
List all C# tutorials.