# MessagePack for C# [![NuGet](https://img.shields.io/nuget/v/MessagePack.svg)](https://www.nuget.org/packages/messagepack) [![Releases](https://img.shields.io/github/release/Cysharp/MessagePack-CSharp.svg)](https://github.com/Cysharp/MessagePack-CSharp/releases) The extremely fast [MessagePack](https://msgpack.org/) serializer for C#. Rebuilt from scratch, v4 brings performance that leaves the competition behind, state-of-the-art features such as first-class support for C# 15 `union` types and Native AOT, and the security a post-AI era demands, reviewed over and over. ![Serialize and deserialize of the Stack Overflow Answer type, mean time in nanoseconds. MessagePack for C# is the fastest in both directions, and its map form is ahead of every other library in the chart.](https://raw.githubusercontent.com/Cysharp/MessagePack-CSharp/master/doc/MessagePack-benchmark.png) For the details on performance, see the [Performance](#performance) section. MessagePack for C# is built on three principles, and each of them holds without configuring anything: * **Performant by default.** As the chart shows, the default settings are tuned for maximum performance. With a source-generator-first design, the formatters of your types are generated at compile time, and the same formatters run at full speed on Native AOT. * **Secure by default.** The default configuration is the one for untrusted data, with no mode to switch on. Strengthened security measures guard against maliciously crafted data. * **Version-tolerant by explicit declaration.** Your C# types are the schema. Explicit, declarative annotations are the default, and they are what makes schema evolution safe. ## Installation This library is distributed via NuGet. Target frameworks are `netstandard2.0`, `netstandard2.1`, `net9.0`, `net10.0` and `net11.0`. ```bash dotnet add package MessagePack ``` The `MessagePack` package contains the serializer, the attributes, the source generator and the analyzers. The following packages are optional additions, such as compression: | Package | What it is | |---|---| | `MessagePack.LZ4` | LZ4 compression, including the v3-compatible `Lz4Block` / `Lz4BlockArray` formats. See [Compression](#compression). | | `MessagePack.Zstandard` | Zstandard compression. See [Compression](#compression). | | `MessagePack.AspNetCoreMvcFormatter` | ASP.NET Core MVC input/output formatters for `application/x-msgpack` (`net10.0`). See [ASP.NET Core](#aspnet-core-mvc--signalr). | | `MessagePack.SignalR` | The SignalR `messagepack` hub protocol (`net10.0`). See [ASP.NET Core](#aspnet-core-mvc--signalr). | | `MessagePack.UnityShims` | The UnityEngine value types (`Vector3`, `Quaternion`, ...) for servers that talk to Unity clients. See [Unity shims](#unity-shims). | ### Unity For Unity projects, see the [Unity support](#unity-support) section. ### Migration notes from prior versions Migrating from a prior major version? See [these instructions](doc/migration.md). The v3 to v4 guide is [here](doc/migrating_v3-v4.md). The wire format is unchanged: v3 and v4 read each other's data, so migrating changes your code and never your data. ## Quick Start Define the class or struct to be serialized and annotate it with `[MessagePackObject]`. Annotate each member to serialize (fields as well as properties) with `[Key]`. ```csharp [MessagePackObject] public class MyClass { // Key attributes take a serialization index (or a string name). // The values must be unique, and versioning has to be considered as well. [Key(0)] public int Age { get; set; } [Key(1)] public string? FirstName { get; set; } [Key(2)] public string? LastName { get; set; } // Public members that should not be serialized are annotated with [IgnoreMember]. [IgnoreMember] public string FullName => FirstName + LastName; } ``` Call `MessagePackSerializer.Serialize` / `Deserialize` to convert data. ```csharp var mc = new MyClass { Age = 99, FirstName = "hoge", LastName = "huga", }; // Call Serialize/Deserialize, that's all. byte[] bytes = MessagePackSerializer.Serialize(mc); MyClass mc2 = MessagePackSerializer.Deserialize(bytes); ``` MessagePack for C# treats your C# types as the serialization schema, the way a `.proto` file or a JSON Schema is one. That is why `[MessagePackObject]` is required by default, on the type and on every user-defined type reachable from it. It keeps the wire format under strict control and makes the schema resilient to incidental changes to a class during development. A missing annotation is reported by an analyzer at compile time, before anything runs, and a code fix adds it for you. A key is either an `int`, which serializes the object as a MessagePack array, or a `string`, which serializes it as a map. See [Object Serialization](#object-serialization) for details. By default these calls use `MessagePackSerializerOptions.Default`, the options meant for JIT. They include work that Native AOT cannot run, such as creating the formatter of a `T[]` or a `List` at run time, so building for Native AOT reports a warning. On Native AOT, pass `MessagePackSerializerOptions.DefaultAot` explicitly: ```csharp byte[] bytes = MessagePackSerializer.Serialize(mc, MessagePackSerializerOptions.DefaultAot); MyClass mc2 = MessagePackSerializer.Deserialize(bytes, MessagePackSerializerOptions.DefaultAot); ``` This is how MessagePack for C# offers everything on JIT and a safe Native AOT at the same time: what Native AOT cannot run is reported when you build, not when it runs. See [Native AOT](#native-aot) for details. ## Analyzer The source generator and its analyzers ship inside the `MessagePack` package and run in every project that references it. * The generator produces a formatter for each `[MessagePackObject]` type at compile time, so nothing is generated at startup and the types work on Native AOT. * The analyzers report mistakes as you type: a member type nothing can serialize, a duplicate or missing `[Key]`, a constructor that cannot be matched to the members, large gaps in the key numbers, and more. A type that is serialized by a formatter the analyzer cannot see (one you compose into the options at run time) is declared with an assembly-level attribute, which silences the warning for members of that type: ```csharp [assembly: MessagePackKnownType(typeof(System.Drawing.Color))] ``` ## Built-in supported types These types can be serialized by default: * Primitives (`int`, `string`, etc...), `enum`s, `Nullable<>`, `Lazy<>` * `TimeSpan`, `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly` * `Guid`, `Uri`, `Version`, `StringBuilder`, `decimal`, `BitArray`, `IPAddress`, `IPEndPoint` * `BigInteger`, `Complex`, `Half`, `Rune`, `Int128`, `UInt128`, `Index`, `Range` * `byte[]`, `Memory<>`, `ReadOnlyMemory<>`, `ReadOnlySequence<>`, `ArraySegment<>` * `System.Numerics.Vector2`, `Vector3`, `Vector4`, `Quaternion`, `Plane`, `Matrix3x2`, `Matrix4x4` * `T[]`, `T[,]`, `T[,,]`, `T[,,,]` * `KeyValuePair<,>`, `Tuple<,...>`, `ValueTuple<,...>` * `List<>`, `LinkedList<>`, `Queue<>`, `Stack<>`, `HashSet<>`, `SortedSet<>`, `PriorityQueue<,>` * `ReadOnlyCollection<>`, `ObservableCollection<>`, `ReadOnlyObservableCollection<>` * `Dictionary<,>`, `SortedDictionary<,>`, `SortedList<,>`, `OrderedDictionary<,>`, `ReadOnlyDictionary<,>`, `ILookup<,>`, `IGrouping<,>` * `IList<>`, `ICollection<>`, `IEnumerable<>`, `ISet<>`, `IReadOnlyList<>`, `IReadOnlyCollection<>`, `IReadOnlySet<>`, `IDictionary<,>`, `IReadOnlyDictionary<,>` * `ConcurrentBag<>`, `ConcurrentQueue<>`, `ConcurrentStack<>`, `ConcurrentDictionary<,>` * Immutable collections (`ImmutableArray<>`, `ImmutableList<>`, `ImmutableDictionary<,>`, etc) and `FrozenDictionary<,>` / `FrozenSet<>` * Non-generic `IList`, `IDictionary`, `ICollection`, `IEnumerable` * Custom implementations of `ICollection<>` or `IDictionary<,>` with a parameterless constructor * Custom implementations of `IList` or `IDictionary` with a parameterless constructor Types that do not exist in .NET Standard (`DateOnly`, `Half`, `Int128`, ...) are supported on `net9.0` and later. The .NET 11 numeric types (`BFloat16`, `Decimal32`, `Decimal64`, `Decimal128`, `Complex`) are supported on `net11.0`. `System.Type`, `ExpandoObject`, `CultureInfo` and `TimeZoneInfo` are supported but opt-in, because reading them takes a name from the payload and looks it up in the runtime or the operating system. See [Security](#security). `DateTime` is serialized in the [MessagePack timestamp format](https://github.com/msgpack/msgpack/blob/master/spec.md#formats-timestamp): it is converted to UTC and loses its `Kind`. With `DotNetOptimized` (or `NativeDateTimeFormatterFactory`), `DateTime` is written in .NET's own binary representation, which keeps the `Kind` but is not readable from other platforms. For Unity's `Vector3` and friends see [Unity support](#unity-support). You can add support for your own types with [custom formatters](#low-level-api-imessagepackformatter). `MessagePack.Nil` is the built-in type representing null/void in MessagePack for C#. ## Object Serialization MessagePack for C# can serialize your own `class` or `struct` types. By default, serializable types must be annotated with `[MessagePackObject]` and their members with `[Key]`. Keys are either indexes (`int`) or strings. With indexes the object is written as a MessagePack array, which is faster and smaller. With strings it is written as a map. `[MessagePackObject(keyAsPropertyName: true)]` uses the member names as string keys, so members need no `[Key]`. `[MessagePackObject(KeyNamingPolicy.CamelCase)]` does the same and converts the names; the policies are those of `JsonNamingPolicy` (`CamelCase`, `SnakeCaseLower`, `KebabCaseLower`, ...). ```csharp [MessagePackObject] public class Sample1 { [Key(0)] public int Foo { get; set; } [Key(1)] public int Bar { get; set; } } [MessagePackObject] public class Sample2 { [Key("foo")] public int Foo { get; set; } [Key("bar")] public int Bar { get; set; } } [MessagePackObject(keyAsPropertyName: true)] public class Sample3 { // No need for a Key attribute public int Foo { get; set; } // To ignore a public member, use the IgnoreMember attribute [IgnoreMember] public int Bar { get; set; } } [MessagePackObject(KeyNamingPolicy.CamelCase)] public class Sample4 { public int FooBar { get; set; } } // ConvertToJson is for diagnostics: it renders a MessagePack binary as JSON, to see what was written. // [10,20] Console.WriteLine(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(new Sample1 { Foo = 10, Bar = 20 }))); // {"foo":10,"bar":20} Console.WriteLine(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(new Sample2 { Foo = 10, Bar = 20 }))); // {"Foo":10} Console.WriteLine(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(new Sample3 { Foo = 10, Bar = 20 }))); // {"fooBar":10} Console.WriteLine(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(new Sample4 { FooBar = 10 }))); ``` All public instance members (fields as well as properties) are serialized. To leave one out, annotate it with `[IgnoreMember]`. The type itself must be `public` or `internal`. Should you use an indexed key or a string key? We recommend indexed keys for faster serialization and a more compact binary. String keys carry the member names, which helps when debugging and when other languages read the data. Be careful about versioning when a class changes. * A member whose key is missing from the data keeps the value the type gives it: its initializer, or `default`. An `init` member is the exception and always falls back to `default`; see [`init` and `required` members](#init-and-required-members). A `required` member, or a constructor parameter without a default value, that is missing throws. * Indexed keys should start at 0 and be sequential. Do not reuse the index of a removed member; keep the member (marked `[Obsolete]`) until every reader has been updated. * Gaps in the indexes cost space, because the array is padded with nil: ```csharp [MessagePackObject] public class IntKeySample { [Key(3)] public int A { get; set; } [Key(10)] public int B { get; set; } } // [null,null,null,0,null,null,null,null,null,null,0] Console.WriteLine(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(new IntKeySample()))); ``` Nullable annotations are part of the contract. In a `#nullable enable` context, a member declared non-nullable (`string Name`) rejects nil when it is read and null when it is written. Declare the member `string?` when null is a valid value. The check is controlled by `ValidateNullableAnnotations` on the [resolver](#main-extension-point-messagepackformatterfactory). ### Private members By default, private members are not serialized. To serialize non-public members, set `AllowPrivate` on the type and declare the type `partial`: ```csharp [MessagePackObject(AllowPrivate = true)] public partial class PrivateSample { [Key(0)] int x; public void SetX(int v) => x = v; public int GetX() => x; } ``` ### Serializing readonly/immutable object members (SerializationConstructor) MessagePack for C# supports immutable objects. For example, this struct can be serialized and deserialized: ```csharp [MessagePackObject] public struct Point { [Key(0)] public readonly int X; [Key(1)] public readonly int Y; public Point(int x, int y) { this.X = x; this.Y = y; } } var data = new Point(99, 9999); var bin = MessagePackSerializer.Serialize(data); // Okay to deserialize an immutable object var point = MessagePackSerializer.Deserialize(bin); ``` Constructor parameters are matched to members by name, ignoring case (`x` binds to `X`). A constructor whose parameters cannot be matched is reported at compile time. When a type has several constructors, mark the one to use with `[SerializationConstructor]`. ```csharp [MessagePackObject] public struct Point { [Key(0)] public readonly int X; [Key(1)] public readonly int Y; public Point(int x) { this.X = x; this.Y = -1; } [SerializationConstructor] public Point(int x, int y) { this.X = x; this.Y = y; } } ``` A constructor parameter with a default value (`string nick = ""`) receives that default when the data does not contain it. ### `record` types Records with a primary constructor work the same way. ```csharp // use the property names as keys [MessagePackObject(true)] public record Point(int X, int Y); // use property: to put the Key on the generated property [MessagePackObject] public record Point([property: Key(0)] int X, [property: Key(1)] int Y); // or use explicit properties [MessagePackObject] public record Person { [Key(0)] public string? FirstName { get; init; } [Key(1)] public string? LastName { get; init; } } ``` ### `init` and `required` members * An `init` member that the data does not contain is set to `default`, not to its initializer (`{ get; init; } = 3` reads `0`). Use a `set` accessor where the initializer must survive missing data. * A `required` member that the data does not contain throws. The check is controlled by `ValidateRequiredMembers` on the resolver. ### Serialization Callback Objects implementing `IMessagePackSerializationCallbackReceiver` receive `OnBeforeSerialize` and `OnAfterDeserialize` calls. ```csharp [MessagePackObject] public class SampleCallback : IMessagePackSerializationCallbackReceiver { [Key(0)] public int Key { get; set; } public void OnBeforeSerialize() { Console.WriteLine("OnBefore"); } public void OnAfterDeserialize() { Console.WriteLine("OnAfter"); } } ``` ### Circular references A type with `AllowCircularReferences = true` writes a repeated reference to the same instance as a back-reference, so a graph with cycles or shared references round-trips as it is. ```csharp [MessagePackObject(AllowCircularReferences = true)] public class Node { [Key(0)] public int Value { get; set; } [Key(1)] public Node? Next { get; set; } } var a = new Node { Value = 1 }; a.Next = new Node { Value = 2, Next = a }; // a cycle var bytes = MessagePackSerializer.Serialize(a); var back = MessagePackSerializer.Deserialize(bytes); // back.Next.Next == back ``` This is available for source-generated types only, and the back-reference is a v4-specific format (ext code 97) that other MessagePack implementations do not understand. ### Enums as names Enums are written as their integer value by default. `EnumAsString = true` writes the enums of a type's members as their names instead, the form other languages usually expect next to a map of member names. ```csharp [MessagePackObject(KeyNamingPolicy.CamelCase, EnumAsString = true)] public class Order { public Status Status { get; set; } // "Shipped" public List? History { get; set; } // ["Created", "Shipped"] public Dictionary? Counts { get; set; } // {"Created": 1} public Customer? Customer { get; set; } // Customer's own [MessagePackObject] decides its enums } ``` The setting reaches enum members and the enums inside a member's arrays, `Nullable`, lists, sets, dictionaries (keys and values) and other built-in collections. `[EnumMember(Value = "...")]` renames a value, and a `[Flags]` combination is written as `"A, B"`. Reading requires a name; an integer throws. For a single enum type, annotate the enum with `[MessagePackFormatter(typeof(EnumAsStringFormatterFactory))]`. On a member, the same attribute applies to that member only; the member has to be of the enum type itself, not a collection of it. ```csharp // on the enum: every use of Status is written by name, inside collections too [MessagePackFormatter(typeof(EnumAsStringFormatterFactory))] public enum Status { Created, Shipped, } // or on one member [MessagePackObject] public class Order { [Key(0)] [MessagePackFormatter(typeof(EnumAsStringFormatterFactory))] public Status Status { get; set; } } ``` To write every enum as its name everywhere, without touching the types, put `GenericEnumAsStringFormatterFactory` first in the chain: ```csharp var options = new MessagePackSerializerOptions( MessagePackFormatterFactory.Combine(new GenericEnumAsStringFormatterFactory(), MessagePackFormatterFactory.Default)); ``` ## Union MessagePack for C# supports serializing interface-typed and abstract class-typed objects. It behaves like `XmlInclude` or `ProtoInclude`. In MessagePack for C# this is called a union. Annotate the base type with `[MessagePackObject]` and one `[UnionTag]` per derived type; the tags must be unique. ```csharp [MessagePackObject] [UnionTag(0)] [UnionTag(1)] public interface IUnionSample { } [MessagePackObject] public class FooClass : IUnionSample { [Key(0)] public int XYZ { get; set; } } [MessagePackObject] public class BarClass : IUnionSample { [Key(0)] public string? OPQ { get; set; } } // --- IUnionSample data = new BarClass { OPQ = "FooBar" }; // Serialize an interface-typed object. var bin = MessagePackSerializer.Serialize(data); // A union is serialized as a two-element array, [tag, object] // [1,["FooBar"]] Console.WriteLine(MessagePackSerializer.ConvertToJson(bin)); // Deserialize again. var reData = MessagePackSerializer.Deserialize(bin); switch (reData) { case FooClass x: Console.WriteLine(x.XYZ); break; case BarClass x: Console.WriteLine(x.OPQ); break; } ``` Targets without generic attributes (`netstandard`, Unity) use the `[UnionTag(typeof(FooClass), 0)]` form. Abstract classes work the same way. A derived type cannot reuse a key of its base type, because both are written into one array or map. ```csharp [MessagePackObject] [UnionTag(0)] [UnionTag(1)] public abstract class ParentUnionType { [Key(0)] public int MyProperty { get; set; } } [MessagePackObject] public class SubUnionType1 : ParentUnionType { [Key(1)] public int MyProperty1 { get; set; } } [MessagePackObject] public class SubUnionType2 : ParentUnionType { [Key(1)] public int MyProperty2 { get; set; } } ``` The C# 15 `closed` hierarchies and `union` types are supported too. For a `closed` hierarchy the analyzer reports a derived type that is missing its `[UnionTag]`, so prefer `closed` where you can. ```csharp [MessagePackObject] [UnionTag(0)] [UnionTag(1)] public closed class Pet { [Key(0)] public string? Name { get; set; } } [MessagePackObject] [UnionTag(0)] [UnionTag(1)] public union IntOrString(int, string); ``` ## Unknown members Like the unknown fields of Protocol Buffers: a `[MessagePackObject]` type can declare one member of type `MessagePackUnknownMembers` (without `[Key]`). The members a newer writer added are kept there and written back on re-serialization, so a service running an older version does not drop the fields it does not know. ```csharp [MessagePackObject(true)] public class Packet { public int Id { get; set; } public MessagePackUnknownMembers? Unknown { get; set; } // catches the members this version does not know } var packet = MessagePackSerializer.Deserialize(bytesFromNewerWriter); var bytes = MessagePackSerializer.Serialize(packet); // includes the members the newer writer added ``` It cannot be combined with `AllowCircularReferences`. ## Surrogates For a type you cannot annotate (a third-party type, or one whose constructor enforces invariants), declare a `struct` that is serialized in its place. The target type needs no attribute. ```csharp // a type you cannot change public sealed class Money { public Money(decimal amount, string currency) { ... } public decimal Amount { get; } public string Currency { get; } } [MessagePackObject] public readonly record struct MoneySurrogate([property: Key(0)] decimal Amount, [property: Key(1)] string Currency) : IMessagePackSurrogate { public MoneySurrogate ToSurrogate(Money value) => new(value.Amount, value.Currency); public Money ToTarget() => new(Amount, Currency); } // Money is now serializable: ["100","JPY"] var bytes = MessagePackSerializer.Serialize(new Money(100m, "JPY")); ``` ## Object Type Serialization A value in an `object`-typed slot is serialized by its runtime type. ```csharp [MessagePackObject] public class ObjectFieldType { [Key(0)] public object? Anything { get; set; } } var objects = new object[] { 1, "aaa", new ObjectFieldType { Anything = 9999 } }; var bin = MessagePackSerializer.Serialize(objects); // [1,"aaa",[9999]] Console.WriteLine(MessagePackSerializer.ConvertToJson(bin)); ``` The type is not written to the data, so deserializing into `object` behaves as described in [Untyped Deserialization](#untyped-deserialization). Runtime-type dispatch is not available on Native AOT, where an `object` slot accepts the primitive values only. ## Untyped Deserialization `MessagePackSerializer.Deserialize` converts the data to primitive values according to what the data contains: `bool`, the integer types, `float`, `double`, `DateTime`, `string`, `byte[]`, `object[]` for arrays and `Dictionary` for maps. An integer comes back in the width it was written with, so a small `int` is read as `byte`. The keys of a map are strings in most data, and then `Dictionary` is the more convenient target. The keys are read as strings and the values as above: ```csharp // blob is the MessagePack form of {"Name":"foobar","Items":[1,10,100,1000]} var map = MessagePackSerializer.Deserialize>(blob); Console.WriteLine(map["Name"]); // foobar // an array is an object[]; 100 fits one byte, so it comes back as a byte var items = (object[])map["Items"]; Console.WriteLine(items[2]); // 100 ``` A map nested in a value is a `Dictionary`. With `DefaultAot`, `Deserialize` works as it is, and `Dictionary` is declared as a root with `[MessagePackSerializable>]`; see [Native AOT](#native-aot). ## Native AOT Types marked with `[MessagePackObject]` are serialized by source-generated formatters, so they work on Native AOT as they are. The default chain additionally creates formatters at run time for shapes such as `Person[]` or `List`, which Native AOT does not allow. Publishing for Native AOT reports a warning where that would happen. To clear the warnings, pass `MessagePackSerializerOptions.DefaultAot`: ```csharp var person = new Person { Id = 1, Name = "neuecc" }; byte[] bytes = MessagePackSerializer.Serialize(person, MessagePackSerializerOptions.DefaultAot); Person back = MessagePackSerializer.Deserialize(bytes, MessagePackSerializerOptions.DefaultAot); ``` `DefaultAot` serves the `[MessagePackObject]` types and the types of their members. A type that is only ever used as the root of a call, such as `Person[]`, has to be declared so that the generator prepares it: ```csharp [MessagePackSerializable] public partial class MySerializationRoots { } ``` Targets without generic attributes (`netstandard`, Unity) use the `[MessagePackSerializable(typeof(Person[]))]` form. A generic `[MessagePackObject]` type is prepared by the generator of the assembly that declares it, and by no other. With `Envelope` in a library, `DefaultAot` serves `Envelope` only if the library itself has a member of that type or declares it with `[MessagePackSerializable>]`; the same declaration in the application does nothing (warning MsgPack022). When the type argument is a type of the application, which the library cannot name, derive a class in the application and serialize that. It has the same format: ```csharp [MessagePackObject] public class OrderEnvelope : Envelope { } ``` Not available with `DefaultAot`: types without attributes (`WithContractless`), `[DataContract]` types, [Typeless](#typeless), and serializing an `object` slot by its runtime type. ## Security Deserializing data from an untrusted source can introduce security vulnerabilities in your application. Untrusted data may arrive over the network, or come from storage that has been tampered with. The default configuration is the one meant for untrusted data. Malformed data that cannot be deserialized throws `MessagePackSerializationException`. | Protection | Default | Where to change it | |---|---|---| | Nesting depth | 500 levels | `options with { MaxDepth = ... }` | | Bytes buffered per message from a `Stream` / `PipeReader` | 64 MB | `options with { MaxBufferedMessageSize = ... }` | | Decompressed size per message | 64 MB | `WithLz4Block(maxDecompressedSize)` and the other compression methods | | Hash-flooding-resistant dictionaries and sets | on | `HashFloodingResistant` on the resolver | | Length headers larger than the remaining data | rejected | always on | Independently of `MaxDepth`, nesting that would exhaust the thread's stack throws `MessagePackSerializationException` instead of crashing the process. That check is sized for frames of a few kilobytes: a generated type with many or large members asks for stack at every level, but a value type of several kilobytes that another formatter carries through every level (a collection or a tuple of it, a formatter of your own, or a type the data names under `LoadAnyType`) is not covered. The hash-flooding protection covers the keys the library can hash itself: the primitive, date and time types, `decimal`, `Guid`, enums, `object` and `string`. A tuple, `KeyValuePair`, `Version`, `BigInteger` or a key type of your own hashes with its own `GetHashCode` and is not protected, whatever that is built from (`HashCode.Combine` is seeded per process, but keys that collide under every seed can be computed). Give such a collection a comparer of your own (a member initialized with one keeps it), or do not key a collection read from untrusted data by it. Some features are deliberately not part of the default configuration, because they act on names supplied by the data: * `System.Type`, `ExpandoObject`, `CultureInfo` and `TimeZoneInfo` have to be enabled by composing their factory (`TypeFormatterFactory`, `ExpandoObjectFormatterFactory`, `CultureInfoFormatterFactory`, `TimeZoneInfoFormatterFactory`) before the default one. Enable them for trusted data only. * [Typeless](#typeless) instantiates the types named in the data. With untrusted data, use `TypelessTypeLoader.AllowedTypes`, never `LoadAnyType`. These protections harden against common attacks. They are not a complete security solution in themselves; also enforce an appropriate message-size limit in your application. ## Performance The performance of a serializer depends on the kind of data. MessagePack for C# v4 is tuned carefully so that it performs at the top whatever the input. Serializers are also normally used with their default settings, and the analyzer support applies most strongly to the default. That is why, of the two modes MessagePack has for objects, array and map, MessagePack for C# makes array, the one with the higher performance ceiling, the default. ### POCO For a fair benchmark the subject is the Stack Overflow `Answer` type from [Jil](https://github.com/kevin-montrose/jil): a fairly large type with more than 20 members, including nested types. #### Serialize | Method | Mean | Allocated | |---|---:|---:| | **MessagePack for C# v4 (array/default)** | 435.8 ns | 1.65 KB | | MessagePack for C# v4 (map) | 507.4 ns | 2.84 KB | | Nerdbank.MessagePack (array) | 985.4 ns | 1.65 KB | | BcsSharp | 1,081.0 ns | 1.78 KB | | **MessagePack for C# v3 (array/default)** | 1,149.9 ns | 1.65 KB | | Orleans | 1,445.8 ns | 1.91 KB | | REDox.MessagePack (map) | 1,464.1 ns | 2.91 KB | | MessagePack for C# v3 (map) | 1,468.3 ns | 2.84 KB | | **Nerdbank.MessagePack (map/default)** | 1,570.8 ns | 2.84 KB | | protobuf-net | 1,751.6 ns | 5.32 KB | | ShapeShift.MsgPack (array) | 1,844.9 ns | 2.98 KB | | ShapeShift.MsgPack (map) | 2,383.1 ns | 3.09 KB | | System.Text.Json | 3,037.4 ns | 5.01 KB | | System.Text.Json source-gen | 3,390.4 ns | 3.63 KB | | ShapeShift.Json | 3,441.5 ns | 3.81 KB | | ShapeShift.Protobuf | 5,348.9 ns | 21.88 KB | | Newtonsoft.Json | 5,737.1 ns | 21.48 KB | #### Deserialize | Method | Mean | Allocated | |---|---:|---:| | **MessagePack for C# v4 (array/default)** | 853.0 ns | 4.65 KB | | MessagePack for C# v4 (map) | 1,125.0 ns | 4.65 KB | | BcsSharp | 1,460.6 ns | 4.67 KB | | **MessagePack for C# v3 (array/default)** | 1,703.5 ns | 4.65 KB | | Orleans | 1,747.9 ns | 4.61 KB | | Nerdbank.MessagePack (array) | 1,840.1 ns | 4.65 KB | | protobuf-net | 1,994.0 ns | 4.72 KB | | MessagePack for C# v3 (map) | 2,633.9 ns | 4.65 KB | | REDox.MessagePack (map) | 3,147.8 ns | 4.65 KB | | ShapeShift.MsgPack (array) | 3,432.7 ns | 8.91 KB | | **Nerdbank.MessagePack (map/default)** | 3,516.5 ns | 4.65 KB | | System.Text.Json source-gen | 5,437.2 ns | 5.12 KB | | System.Text.Json | 5,452.0 ns | 5.12 KB | | ShapeShift.Protobuf | 6,213.4 ns | 12.55 KB | | ShapeShift.MsgPack (map) | 6,499.4 ns | 14.08 KB | | ShapeShift.Json | 7,867.0 ns | 14 KB | | Newtonsoft.Json | 10,601.0 ns | 17.51 KB | ### int / bool Values as small as a primitive measure the serializer's own setup cost. The measurement alternates `int` and `bool` calls, which rules out two things that do not happen in production: optimizations that come from profiling a single type, and benchmark-hack style type caches. #### Serialize | Method | Mean | Allocated | |---|---:|---:| | **MessagePack for C# v4** | 13.587 ns | 64 B | | Nerdbank.MessagePack | 28.391 ns | 64 B | | MessagePack for C# v3 | 32.580 ns | 64 B | | System.Text.Json | 62.928 ns | 64 B | #### Deserialize | Method | Mean | Allocated | |---|---:|---:| | **MessagePack for C# v4** | 5.756 ns | - | | MessagePack for C# v3 | 33.222 ns | - | | Nerdbank.MessagePack | 47.620 ns | - | | System.Text.Json | 47.825 ns | - | ### Whole documents For larger payloads the subject is the corpus of the [RE:Dox](https://github.com/CAPCOM-TD-OSS/REDox) serializer benchmark: twelve JSON documents from [simdjson-data](https://github.com/simdjson/simdjson-data), bound to the POCO graphs RE:Dox declares for them and serialized and deserialized whole (9 KB to 2.8 MB as MessagePack). The documents are of different kinds: long strings, small objects in bulk, dictionaries, arrays of floating-point numbers. Every row holds the same data and reads back its own output. The charts and the tables are the mean time in μs. The charts draw the five documents between 100 KB and 500 KB as MessagePack, whose times fit one axis; the tables hold all twelve, and their `geometric mean` row is the geometric mean of the ratio to MessagePack for C# (array) over the twelve documents. Concurrent GC is off for these runs: several documents allocate arrays of 85 KB or more on every call, and with a background GC in play those rows swing with the collector's timing rather than with the serializer. #### Serialize ![The RE:Dox corpus, serialize: the mean time of each library on citm_catalog, mesh, random, twitter and update-center, in microseconds; the numbers are in the table below.](https://raw.githubusercontent.com/Cysharp/MessagePack-CSharp/master/doc/MessagePack-benchmark-redox-serialize.png) | Document | **MessagePack for C# (array/default)** | MessagePack for C# (map) | Nerdbank.MessagePack (array) | **Nerdbank.MessagePack (map/default)** | System.Text.Json | |---|---:|---:|---:|---:|---:| | apache_builds | 22.7 | 22.1 | 35.7 | 46.0 | 103.5 | | canada | 487.8 | 500.8 | 546.8 | 564.6 | 8,514.1 | | citm_catalog | 102.6 | 185.5 | 205.7 | 375.4 | 776.2 | | github_events | 8.5 | 10.5 | 14.9 | 21.4 | 36.1 | | gsoc-2018 | 777.5 | 872.6 | 950.6 | 1,045.7 | 2,812.7 | | instruments | 6.9 | 11.6 | 33.8 | 60.3 | 125.6 | | marine_ik | 599.5 | 602.1 | 906.3 | 978.9 | 7,344.9 | | mesh | 123.9 | 129.4 | 171.2 | 179.2 | 2,075.2 | | numbers | 25.7 | 25.6 | 26.1 | 26.1 | 592.4 | | random | 225.7 | 278.1 | 319.9 | 425.1 | 1,030.2 | | twitter | 196.6 | 300.3 | 293.9 | 446.6 | 763.9 | | update-center | 293.5 | 349.0 | 388.4 | 488.7 | 741.7 | | geometric mean | 1.00x | 1.21x | 1.57x | 2.01x | 7.58x | #### Deserialize ![The RE:Dox corpus, deserialize: the mean time of each library on citm_catalog, mesh, random, twitter and update-center, in microseconds; the numbers are in the table below.](https://raw.githubusercontent.com/Cysharp/MessagePack-CSharp/master/doc/MessagePack-benchmark-redox-deserialize.png) | Document | **MessagePack for C# (array/default)** | MessagePack for C# (map) | Nerdbank.MessagePack (array) | **Nerdbank.MessagePack (map/default)** | System.Text.Json | |---|---:|---:|---:|---:|---:| | apache_builds | 68.4 | 72.5 | 81.9 | 108.9 | 138.1 | | canada | 1,114.9 | 1,091.6 | 1,540.5 | 1,485.6 | 9,767.8 | | citm_catalog | 168.8 | 209.9 | 345.3 | 742.8 | 1,456.2 | | github_events | 22.7 | 25.4 | 35.6 | 56.8 | 74.2 | | gsoc-2018 | 1,015.7 | 1,041.5 | 1,125.2 | 1,394.1 | 3,350.8 | | instruments | 21.4 | 39.5 | 56.7 | 144.8 | 176.2 | | marine_ik | 791.7 | 869.1 | 1,533.5 | 2,068.1 | 8,985.3 | | mesh | 135.2 | 132.7 | 365.3 | 365.2 | 2,271.5 | | numbers | 4.2 | 4.2 | 27.9 | 28.1 | 469.7 | | random | 335.8 | 363.6 | 437.4 | 686.4 | 1,519.3 | | twitter | 224.4 | 299.4 | 334.8 | 563.3 | 1,039.4 | | update-center | 394.7 | 445.3 | 533.7 | 835.6 | 1,071.3 | | geometric mean | 1.00x | 1.14x | 1.83x | 2.63x | 7.10x | Contract for contract, MessagePack for C# is ahead of Nerdbank.MessagePack on every document in both directions, and its map form is ahead of Nerdbank.MessagePack's array form on 23 of the 24 cells. Default against default, the geometric mean is 2.0x on serialize and 2.6x on deserialize. System.Text.Json is 7.6x and 7.1x behind. `numbers` is a bare `double[]`, which has no array or map form, so its two columns per library are the same measurement. Its serialize row is the collector's: the 88 KB result is a large-object allocation per call, and every MessagePack row pays the same for it. ### Next to simdjson [simdjson](https://github.com/simdjson/simdjson) is the JSON library everyone measures against, in C++. Its README measures `twitter.json` to and from three C++ structs: 6 members of each status and 9 of its user. We ran the same task, with the same three structs in C#, and built simdjson's own benchmark with GCC 16.2 to run it on the same machine. simdjson reports GB of JSON per second; on this machine that is 18.9 GB/s for the 82 KB those structs serialize to and 5.9 GB/s for the 632 KB file, which is 4.33 μs and 107.7 μs. The charts and the table compare time, because the libraries here do not write or read the same bytes. ![simdjson's twitter.json benchmark, serialize, time in microseconds: MessagePack for C# 2.95 (array) and 3.73 (map), simdjson (C++) 4.33, Nerdbank.MessagePack 8.57 and 13.39, System.Text.Json 85.32.](https://raw.githubusercontent.com/Cysharp/MessagePack-CSharp/master/doc/MessagePack-benchmark-simdjson-serialize.png) ![simdjson's twitter.json benchmark, deserialize, time in microseconds: MessagePack for C# 38.3 (array) and 75.7 (map), Nerdbank.MessagePack 82.4 (array), simdjson (C++) 107.7, Nerdbank.MessagePack 229.0 (map), System.Text.Json 446.0.](https://raw.githubusercontent.com/Cysharp/MessagePack-CSharp/master/doc/MessagePack-benchmark-simdjson-deserialize.png) | | Serialize | Deserialize | |---|---:|---:| | **MessagePack for C# (array/default)** | 2.95 μs | 38.3 μs | | MessagePack for C# (map) | 3.73 μs | 75.7 μs | | simdjson (C++) | 4.33 μs | 107.7 μs | | Nerdbank.MessagePack (array) | 8.57 μs | 82.4 μs | | **Nerdbank.MessagePack (map/default)** | 13.39 μs | 229.0 μs | | System.Text.Json | 85.32 μs | 446.0 μs | The two sides are not the same language, so this is how it is measured: * **Text stays UTF-8.** A C++ `std::string` is UTF-8; a .NET `string` is UTF-16 and would be converted on every member. The members are a `Utf8String` struct with a [custom formatter](#low-level-api-imessagepackformatter) of a few lines that writes its bytes as they are. Nerdbank.MessagePack and System.Text.Json get the same struct through their own converters. * **The output buffer is reused**, through each library's `IBufferWriter` entry point, as in the rows of simdjson's benchmark that reuse theirs. * **Deserializing reads the whole document and keeps the 15 members.** simdjson scans all of `twitter.json` to fill its structs. The MessagePack rows read the whole document too (221 KB as an array, 407 KB as a map), into a type that declares only those members: by their positions in the array form (`[Key(1)]`, `[Key(2)]`, `[Key(4)]`, `[Key(12)]`, ...), by their names in the map form. What the type does not declare is skipped. The benchmark is [SimdjsonTwitterBenchmark.cs](sandbox/DisassembleBenchmark/SimdjsonTwitterBenchmark.cs). ## String interning The MessagePack format has no way to reuse a string within the data, so the deserializer creates a new `string` for every string it reads, even when it equals one read before. When the data contains the same strings again and again, it can be worthwhile to have the deserializer look each string up and reuse the instance. To intern *all* strings, put `StringInterningFormatterFactory` first in the chain: ```csharp static readonly StringInterningFormatterFactory Interning = new StringInterningFormatterFactory(); static readonly MessagePackSerializerOptions InterningOptions = new MessagePackSerializerOptions( MessagePackFormatterFactory.Combine(Interning, MessagePackFormatterFactory.Default)); MessagePackSerializer.Deserialize(data, InterningOptions); ``` If only some members are likely to repeat, apply interning to just those members: ```csharp [MessagePackObject] public class ClassOfStrings { [Key(0)] [MessagePackFormatter(typeof(StringInterningFormatterFactory))] public string? InternedString { get; set; } [Key(1)] public string? OrdinaryString { get; set; } } ``` Each factory instance owns its pool of strings. The pool keeps every distinct string it has seen until you call `Clear()` on the factory, so use interning where the set of values is small (column names, tags), and only with trusted data. A string that is already in the pool is returned without decoding it and without taking a lock. ## Compression MessagePack is a fast and *compact* format, but it is not compression. Compression is provided by separate packages. ```bash dotnet add package MessagePack.LZ4 dotnet add package MessagePack.Zstandard ``` ```csharp static readonly MessagePackSerializerOptions Lz4BlockArrayOptions = MessagePackSerializerOptions.Default.WithLz4BlockArray(); static readonly MessagePackSerializerOptions Lz4BlockOptions = MessagePackSerializerOptions.Default.WithLz4Block(); static readonly MessagePackSerializerOptions Lz4FrameOptions = MessagePackSerializerOptions.Default.WithLz4Frame(); static readonly MessagePackSerializerOptions ZstdFrameOptions = MessagePackSerializerOptions.Default.WithZstandardFrame(); var bin = MessagePackSerializer.Serialize(obj, Lz4BlockArrayOptions); var obj2 = MessagePackSerializer.Deserialize(bin, Lz4BlockArrayOptions); ``` | Method | Format | |---|---| | `WithLz4BlockArray()` | LZ4 blocks inside a MessagePack `ext` (code 98). The data is compressed in chunks, which keeps the buffers out of the large object heap. Compatible with v3. | | `WithLz4Block()` | One LZ4 block inside a MessagePack `ext` (code 99). Slightly better ratio. Compatible with v3. | | `WithLz4Frame()` | The standard LZ4 frame format around the MessagePack data. Other tools and languages can read it. | | `WithZstandardFrame()` | A standard Zstandard frame around the MessagePack data. | `Lz4Block` and `Lz4BlockArray` are formats specific to MessagePack for C#, and either option reads data written with the other. For new uses of LZ4 we recommend `WithLz4Frame()`. The decompressed size of one message is capped at 64 MB by default; each method has an overload that takes `maxDecompressedSize`. `MessagePack.LZ4` (and `MessagePack.Zstandard` below .NET 11) runs on the native libraries of [NativeCompressions](https://github.com/Cysharp/NativeCompressions), so the platforms of that package apply: Windows, Linux and macOS on x64 / arm64, Android, iOS and Mac Catalyst. There is no x86 (32-bit) library, so a .NET Framework executable must set `x64` or a `RuntimeIdentifier`. For Unity, follow the [NativeCompressions README](https://github.com/Cysharp/NativeCompressions#unity). On .NET 11, Zstandard uses the codec bundled with the runtime. Compression is very effective when the data holds many objects with string keys, an array of them for example, because the same names repeat. With int keys you cannot expect as much. So rather than relying on compression, we recommend int keys, which keep the names from repeating in the first place. Compression also costs time, so measure the effect on your own data. ## Hints to achieve maximum performance MessagePack for C# prioritizes performance by default. Some options trade performance for convenience. ### Use indexed keys instead of string keys Indexed keys serialize an object as a MessagePack array, string keys as a map: ```csharp [MessagePackObject] public class Person { [Key(0)] // or [Key("name")] public string? Name { get; set; } [Key(1)] // or [Key("age")] public int Age { get; set; } } ``` * Indexed: `["foobar",999]` * String: `{"name":"foobar","age":999}` Indexed keys are faster in both directions, because no key names are written or looked up, and the binary is smaller. String keys are a simple replacement for JSON, read well from other languages and are less error-prone to version. For maximum performance, use indexed keys. ### Reuse the resolver The formatters are created and cached by the `MessagePackFormatterResolver`, so the resolver is what has to be kept. `MessagePackSerializerOptions` is a light record around it. Deriving options from existing ones, per call if you like, is an intended use: the copies share the resolver and its formatters. ```csharp // this builds a resolver: do it once and keep the result static readonly MessagePackSerializerOptions MyOptions = new MessagePackSerializerOptions( MessagePackFormatterFactory.Combine(new ColorFormatterFactory(), MessagePackFormatterFactory.Default)); // these share the resolver of MyOptions, so they cost next to nothing var deeper = MyOptions with { MaxDepth = 1000 }; var fresh = new MessagePackSerializerOptions(MyOptions.Resolver); ``` What rebuilds every formatter is a new resolver. `new MessagePackSerializerOptions(factory)` and `new MessagePackFormatterResolver(factory)` each create one, so keep those out of the per-call path. ### Use the .NET-optimized formats By default `Guid` and `decimal` are written as strings and `DateTime` in the MessagePack timestamp format, which other languages can read. If the data is only exchanged between .NET applications, `MessagePackSerializerOptions.DotNetOptimized` uses faster binary formats for `Guid`, `decimal`, `DateTime` (keeping its `Kind`), `DateTimeOffset` and `BitArray`. ### Be careful when copying buffers `MessagePackSerializer.Serialize` returns a `byte[]` by default, copied from an internal pooled buffer. To avoid the copy, serialize into an `IBufferWriter`, a `Stream` or a `PipeWriter`. When deserializing, the `ReadOnlySpan` and `ReadOnlySequence` overloads read the data in place. The `Stream` overload first reads the whole message into memory, so prefer the others when you already hold the data. ## Extensions ### ASP.NET Core (MVC / SignalR) ```csharp builder.Services.AddControllers().AddMessagePackFormatters(); // MVC: application/x-msgpack in and out builder.Services.AddSignalR().AddMessagePackProtocol(); // SignalR: the "messagepack" hub protocol ``` Both methods have an overload that takes a `MessagePackSerializerOptions`. `MessagePack.SignalR` is wire-compatible with `Microsoft.AspNetCore.SignalR.Protocols.MessagePack`, which it replaces. Its default options follow that protocol rather than `MessagePackSerializerOptions.Default`: types without attributes are written as maps of member names, enums as their names, and nullable annotations are not enforced. For Native AOT, pass options based on `DefaultAot`, annotate the hub argument types, and compose `EnumAsStringFormatterFactory` for each enum so that the official .NET, JavaScript and Java clients keep reading enum names. ### Unity shims `MessagePack.UnityShims` provides the UnityEngine value types for a .NET server that talks to Unity clients. See [Unity support](#unity-support). ## High-Level API (`MessagePackSerializer`) The `MessagePackSerializer` class is the entry point of MessagePack for C#. | API | Description | | --- | --- | | `Serialize` | Serializes an object graph to MessagePack: returns a `byte[]`, or writes to an `IBufferWriter` or a `Stream`. | | `Deserialize` | Deserializes from a `ReadOnlySpan` (a `byte[]` converts implicitly), a `ReadOnlySequence` or a `Stream`. | | `SerializeAsync` / `DeserializeAsync` | The asynchronous variants for `Stream`, `PipeWriter` and `PipeReader`. | | `SerializeMessagesAsync` / `DeserializeMessagesAsync` | Several messages on one stream. See below. | | `SerializeElementsAsync` / `DeserializeElementsAsync` | One array, written and read element by element. See below. | | `ConvertToJson` | Converts a MessagePack binary to JSON. Useful for debugging. | | `ConvertFromJson` | Converts JSON to a MessagePack binary. | `Serialize` and `Deserialize` also have non-generic overloads that take a `Type`. Every method takes an optional `MessagePackSerializerOptions`. Without it, `MessagePackSerializerOptions.Default` is used. There is no mutable process-wide default: pass your options to each call. ### Multiple MessagePack structures on a single `Stream` Two families of methods put several values on one stream. `SerializeMessagesAsync` concatenates one message per value. `SerializeElementsAsync` writes a single array, element by element, without holding the whole array in memory. Both work over `Stream` and `PipeWriter` / `PipeReader`, and the deserialize side is an `IAsyncEnumerable`. ```csharp // a sequence of messages await MessagePackSerializer.SerializeMessagesAsync(stream, GetEventsAsync()); await foreach (var e in MessagePackSerializer.DeserializeMessagesAsync(stream)) { Handle(e); } // one array, element by element; the data can also be read with Deserialize await MessagePackSerializer.SerializeElementsAsync(stream, events, count: events.Count); await foreach (var e in MessagePackSerializer.DeserializeElementsAsync(stream)) { Handle(e); } ``` If a message cannot be read, the enumeration throws `MessagePackSerializationException` and ends. Over a `PipeReader` or a seekable `Stream`, a complete message that does not deserialize as `T` has been consumed, so a new enumeration continues with the message after it. In every other case there is no position to continue from, so stop reading that stream: bytes that are not MessagePack, a message that is cut off or larger than `MaxBufferedMessageSize`, a non-seekable `Stream`, and any failure inside an element stream. ### Length-prefixed framing To find where a message ends on a `Stream` or a `PipeReader`, the serializer has to walk its tokens. `WithFraming()` puts the byte length in front of every message, so the end is known from the header alone: ```csharp static readonly MessagePackSerializerOptions FramedOptions = MessagePackSerializerOptions.Default.WithFraming(); ``` The length travels as a MessagePack `ext` header (code 95) around the message, a v4-specific envelope, so read the data with the same option. Framing takes the place of compression in the options; the two cannot be combined. ### Populating an existing instance The `Deserialize(source, ref value)` overloads fill an existing instance instead of creating a new one. Collections are cleared and refilled and objects are overwritten member by member, so buffers and pooled objects can be reused. ```csharp var list = new List(capacity: 1024); var state = new GameState(); MessagePackSerializer.Deserialize(bytes, ref list); // refills the same List instance MessagePackSerializer.Deserialize(bytes, ref state); // overwrites the same GameState ``` If the call throws, the instance is left partly overwritten. Fill it again or discard it; do not use what it holds. The same applies to members inside an object: a collection or object that a member initializer created (`List Items { get; set; } = new()`) is filled in place rather than replaced. Do not initialize a member with an instance that is shared between objects, such as a static array: the data overwrites it for all of them. ## Low-Level API (`IMessagePackFormatter`) A formatter serializes one type. The interface is generic over the buffers it writes to and reads from: ```csharp public interface IMessagePackFormatter { void Initialize(MessagePackFormatterResolver resolver); void Serialize(ref TWriteBuffer buffer, ref SerializeState state, T value); void Deserialize(ref TReadBuffer buffer, ref DeserializeState state, ref T value); } ``` Your own types are normally covered by `[MessagePackObject]`. Some types, especially those from third-party libraries or the runtime itself, cannot be annotated. For those, use a [surrogate](#surrogates) or write a formatter. Declare the formatter `partial` and generic over the two buffers; the source generator adds the constraints on the buffer type parameters. ```csharp using MessagePack; /// Serializes a as its ARGB value. public sealed partial class ColorFormatter : IMessagePackFormatter { public void Initialize(MessagePackFormatterResolver resolver) { } public void Serialize(ref TWriteBuffer buffer, ref SerializeState state, Color value) { buffer.WriteInt32(value.ToArgb()); } public void Deserialize(ref TReadBuffer buffer, ref DeserializeState state, ref Color value) { value = Color.FromArgb(buffer.ReadInt32()); } } ``` The read and write methods (`WriteInt32`, `ReadString`, `WriteArrayHeader`, ...) are the buffer extensions described under [`MessagePackPrimitives`](#messagepackprimitives); the tables of [`MessagePackWriter`](#messagepackwriter) and [`MessagePackReader`](#messagepackreader) list them by name. **Important**: a formatter must *read or write exactly one data structure*. The example above writes a single integer. To write more than one element, precede them with an array or map header, and read the entire array or map when deserializing: ```csharp public sealed partial class MySpecialObjectFormatter : IMessagePackFormatter { IMessagePackFormatter stringFormatter = null!; public void Initialize(MessagePackFormatterResolver resolver) { // Get the formatters of nested types here, once. stringFormatter = resolver.GetFormatter(); } public void Serialize(ref TWriteBuffer buffer, ref SerializeState state, MySpecialObject? value) { if (value is null) { buffer.WriteNil(); return; } state.Enter(); buffer.WriteArrayHeader(2); stringFormatter.Serialize(ref buffer, ref state, value.FullName); buffer.WriteInt32(value.Age); state.Exit(); } public void Deserialize(ref TReadBuffer buffer, ref DeserializeState state, ref MySpecialObject? value) { if (buffer.TryReadNil()) { value = null; return; } string? fullName = null; int age = 0; state.Enter(); // Loop over *all* array elements, however many are expected: an older or newer // version of the type may have written a different number of them. var count = buffer.ReadArrayHeader(ref state); for (int i = 0; i < count; i++) { switch (i) { case 0: stringFormatter.Deserialize(ref buffer, ref state, ref fullName); break; case 1: age = buffer.ReadInt32(); break; default: buffer.Skip(); break; } } state.Exit(); value = new MySpecialObject(fullName ?? "", age); } } ``` Rules for formatter code: * Surround the calls into other formatters with `state.Enter()` / `state.Exit()`. This is what enforces `MaxDepth`. * Read array and map headers with the `ref state` overload (`ReadArrayHeader(ref state)`), which checks the declared count against the size of the message. * Serialize `string` and `DateTime` members through the formatter from the resolver, as above, so that options such as string interning and the .NET-optimized formats apply to them. * Use the buffer only through its `ref` parameter. Never copy it into a local, a field or a closure. The analyzers check all four. A formatter is put to use in one of two ways: with [`[MessagePackFormatter]`](#messagepackformatterattribute) on a type or member, or through a [factory](#main-extension-point-messagepackformatterfactory) in the options. ## Primitive API To build or take apart a message by hand, outside a formatter (a protocol envelope around serialized values, for example), there are two levels. `MessagePackPrimitives` reads and writes single tokens over spans. It is what the serializer itself is built on, and it is the one we recommend. `MessagePackWriter` and `MessagePackReader` are the simpler way: they keep the position and manage the memory for you. Both are available on every target framework, Unity included, and the tokens have the same names at every level: `TryWriteInt32`, `buffer.WriteInt32`, `writer.WriteInt32`. ### `MessagePackPrimitives` Static methods that write one token to a `Span` or read one from a `ReadOnlySpan`. They hold no state and never throw. ```csharp Span destination = stackalloc byte[64]; var written = 0; // each call writes one token at the start of the span it is given and reports its size MessagePackPrimitives.TryWriteArrayHeader(destination, 2, out var size); written += size; MessagePackPrimitives.TryWriteString(destination[written..], "Add", out size); written += size; MessagePackPrimitives.TryWriteInt32(destination[written..], requestId, out size); written += size; // destination[..written] is ["Add",42] ReadOnlySpan source = destination[..written]; if (MessagePackPrimitives.TryReadArrayHeader(source, out var count, out size) != DecodeResult.Success) { // not an array, or the data ends inside the header } source = source[size..]; MessagePackPrimitives.TryReadString(source, out var method, out size); source = source[size..]; MessagePackPrimitives.TryReadInt32(source, out var id, out size); ``` There are three families: | Family | Shape | Behaviour | | --- | --- | --- | | `TryWrite...` | `bool TryWriteInt32(Span destination, int value, out int bytesWritten)` | Returns `false` and writes nothing when the destination is too small. | | `TryRead...` | `DecodeResult TryReadInt32(ReadOnlySpan source, out int value, out int tokenSize)` | `Success`; `TokenMismatch` when the next token is of another type or does not fit the requested one; `InsufficientBuffer` when the source ends inside the token. | | `UnsafeWrite...` | `int UnsafeWriteInt32(ref byte destination, int value)` | No bounds check: the caller guarantees the worst-case size of the token, which the `Max...Length` constants give (`MaxInt32Length` is 5). Returns the number of bytes written. This is what generated formatters call. | With `InsufficientBuffer`, `tokenSize` is the number of bytes the token needs, so a reader that receives its data in pieces fetches that much and retries. `TryReadToken` reads any token by its structure, without decoding the value, for skipping and scanning. The same tokens are extension methods on the buffers of [SerializerFoundation](https://github.com/Cysharp/SerializerFoundation), `IWriteBuffer` and `IReadBuffer`: `buffer.WriteInt32(value)`, `buffer.ReadInt32()`. These are the methods a [formatter](#low-level-api-imessagepackformatter) calls. They keep the position, grow the output, and throw `MessagePackSerializationException` on a mismatch or on truncated data. Outside a formatter, create the buffer yourself: ```csharp using SerializerFoundation; var output = new ArrayBufferWriter(); var buffer = new BufferWriterWriteBuffer(output); buffer.WriteArrayHeader(3); buffer.WriteString("Add"); buffer.WriteInt32(requestId); MessagePackSerializer.Serialize(ref buffer, arguments, options); // one value through its formatter buffer.Flush(); var readBuffer = new ReadOnlySpanReadBuffer(output.WrittenSpan); var count = readBuffer.ReadArrayHeader(); var method = readBuffer.ReadString(); var id = readBuffer.ReadInt32(); var args = MessagePackSerializer.Deserialize(ref readBuffer, options); ``` These buffers are ref structs and, like the `Serialize` and `Deserialize` overloads that take one, need `net9.0` or later. ### `MessagePackWriter` The writer collects the message in pooled memory and grows as it goes, so there is no destination to size. Nothing reaches the output before `ToArray` or `WriteTo`, so there is no `Flush`. ```csharp using var writer = new MessagePackWriter(); writer.WriteArrayHeader(3); writer.WriteString("Add"); writer.WriteInt32(requestId); writer.Serialize(arguments, options); // one value through its formatter byte[] bytes = writer.ToArray(); // or writer.WriteTo(span) / WriteTo(bufferWriter) / WriteTo(stream) ``` It is a ref struct that holds pooled memory. Dispose it, and never copy it. | Method | Description | | --- | --- | | `WriteNil` | Writes the MessagePack equivalent of `null`. | | `WriteInt32`, `WriteString`, `WriteBoolean`, `WriteDouble`, ... | Writes a value in the most compact form possible. One method per type. | | `WriteForcedInt32`, ... | Writes an integer in exactly the named MessagePack format, even if a more compact one exists. | | `WriteArrayHeader` / `WriteMapHeader` | Introduces an array or map by the number of elements or key-value pairs. | | `WriteBinary` | Writes a `bin` value. | | `WriteBinHeader` | Writes the header of a `bin` value; the data follows with `WriteRaw`. | | `WriteTimestamp` | Writes a `DateTime` in the MessagePack timestamp format. | | `WriteExtHeader` | Writes the header (type code and length) of an extension value; the data follows with `WriteRaw`. | | `WriteRaw` | Copies bytes to the output without any validation. | | `Serialize` | Writes one value through its formatter. | | `ToArray` / `WriteTo` | Produces the message. | | `BytesWritten` | The number of bytes written so far. | ### `MessagePackReader` The reader reads its source in place and keeps the position. Where the primitives return a `DecodeResult`, its methods throw `MessagePackSerializationException`. ```csharp using var reader = new MessagePackReader(bytes); // ReadOnlyMemory or ReadOnlySequence; ReadOnlySpan on net9.0 and later var count = reader.ReadArrayHeader(); var method = reader.ReadString(); var id = reader.ReadInt32(); var args = reader.Deserialize(options); ``` Like the writer, it is a ref struct to dispose and never to copy. | Method | Description | | --- | --- | | `ReadInt32`, `ReadString`, `ReadBoolean`, ... | Reads a value of the named type. Throws if the data does not match. A number is accepted in any integer format and throws if it does not fit the requested type. | | `ReadNullableInt32`, `ReadNullableBoolean`, `ReadNullableDouble`, ... | Reads a value of the named type, or `null` when the data holds nil. | | `TryReadNil` | Consumes a nil and returns `true`; otherwise leaves the position unchanged and returns `false`. | | `ReadArrayHeader` / `ReadMapHeader` | Reads the header of an array or map and returns the count. | | `ReadStringHeader` / `ReadBinHeader` / `ReadExtHeader` | Reads a header and returns the payload length (`ReadExtHeader` also returns the type code); read the payload with `ReadRaw(length)`. | | `TryReadExtHeader` | Consumes an extension header of the given type code and returns `true`; otherwise leaves the position unchanged and returns `false`. | | `ReadBinary` | Reads a `bin` value into a new array. | | `ReadTimestamp` | Reads a MessagePack timestamp as a UTC `DateTime`. | | `ReadRaw` | Copies the next value, or the given number of bytes, without interpreting it. | | `Skip` | Advances past the next value. An array or map is skipped as a whole. | | `TryPeek` | Returns the next code byte without consuming it. `MessagePackCode` has the constants. | | `NextMessagePackType` | The kind of the next value (`Integer`, `String`, `Array`, ...), without consuming it. | | `Deserialize` | Reads one value through its formatter. | | `BytesConsumed` / `BytesRemaining` / `End` | The position in the source. | ## Main Extension Point (`MessagePackFormatterFactory`) Serialization is configured through three objects: ``` MessagePackSerializerOptions per-call settings: MaxDepth, MaxBufferedMessageSize, compression MessagePackFormatterResolver creates and caches the formatters; holds the validation settings MessagePackFormatterFactory decides which formatter serves which type ``` A factory either returns a formatter for a type or declines. Factories are combined into a chain, and the first factory that serves a type wins, so put overrides before the defaults: ```csharp // Do this once and store it for reuse. static readonly MessagePackSerializerOptions MyOptions = new MessagePackSerializerOptions( MessagePackFormatterFactory.Combine( new ColorFormatterFactory(), // your own types first MessagePackFormatterFactory.Default)); // then the default chain byte[] bytes = MessagePackSerializer.Serialize(myObject, MyOptions); MyObject myObject2 = MessagePackSerializer.Deserialize(bytes, MyOptions); ``` The ready-made chains, each also available as `MessagePackSerializerOptions.`: | Chain | Description | | --- | --- | | `MessagePackFormatterFactory.Default` | Source-generated formatters, built-in types, generic collections, and `[MessagePackObject]` types the generator did not cover. The default of `MessagePackSerializer`. | | `MessagePackFormatterFactory.DefaultAot` | Source-generated and built-in formatters only. For Native AOT, trimmed applications and IL2CPP. | | `MessagePackFormatterFactory.DotNetOptimized` | `Default` with the faster .NET-specific formats for `Guid`, `decimal`, `DateTime`, `DateTimeOffset` and `BitArray`. | | `MessagePackFormatterFactory.DotNetOptimizedAot` | The same on top of `DefaultAot`. | Options that extend a chain: | Method / factory | Description | | --- | --- | | `.WithContractless(allowPrivate: false)` | Serializes types without attributes as maps of member names. | | `.WithTypeless(typeLoader)` | Embeds .NET type names for `object` and abstract slots. See [Typeless](#typeless). | | `.WithUnity()` | The UnityEngine types. See [Unity support](#unity-support). | | `GenericEnumAsStringFormatterFactory` | Writes every enum as its name. | | `StringInterningFormatterFactory` | Reuses equal strings. See [String interning](#string-interning). | | `NativeDateTimeFormatterFactory` | Writes `DateTime` in .NET's binary representation, keeping `Kind`. | | `TypeFormatterFactory`, `ExpandoObjectFormatterFactory`, `CultureInfoFormatterFactory`, `TimeZoneInfoFormatterFactory` | The opt-in types. See [Security](#security). | The resolver has the settings that shape how formatters behave. They are fixed once the resolver is created: ```csharp var resolver = new MessagePackFormatterResolver(MessagePackFormatterFactory.Default) { ValidateNullableAnnotations = false, }; var options = new MessagePackSerializerOptions(resolver); ``` | Setting | Default | Description | | --- | --- | --- | | `ValidateNullableAnnotations` | `true` | Rejects nil / null in members declared non-nullable. | | `ValidateRequiredMembers` | `true` | Throws when a `required` member is missing from the data. | | `HashFloodingResistant` | `true` | Creates dictionaries and sets with a comparer that resists hash-flooding attacks. | | `ThrowOnLegacyFormatter` | `false` | Throws, instead of taking the slower path, when a formatter built for `netstandard` only is involved. See [For library authors](#for-library-authors). | ### Writing a factory To make your formatters available as a package, or to serve several types, write a factory. Declare it `partial`; the source generator supplies the rest. ```csharp using MessagePack; using SerializerFoundation; public sealed partial class ColorFormatterFactory : MessagePackFormatterFactory { #if NET9_0_OR_GREATER public override object? CreateFormatter(Type type) #else public object? CreateFormatter(Type type) where TWriteBuffer : struct, IWriteBuffer where TReadBuffer : struct, IReadBuffer #endif { // Return null for the types this factory does not serve. return type == typeof(Color) ? new ColorFormatter() : null; } } ``` The `#if` is only needed in a project that also targets `netstandard`. A project that targets `net9.0` or later only writes the `override` line. ## MessagePackFormatterAttribute `[MessagePackFormatter]` attaches a formatter to a type or to a single member, like Json.NET's `JsonConverterAttribute`. It names either a formatter that is generic over the two buffers (`typeof(MyFormatter<,>)`) or a factory. On a type, no further registration is needed: ```csharp [MessagePackFormatter(typeof(TemperatureFormatter<,>))] public readonly struct Temperature(double celsius) { public double Celsius => celsius; } public sealed partial class TemperatureFormatter : IMessagePackFormatter { public void Initialize(MessagePackFormatterResolver resolver) { } public void Serialize(ref TWriteBuffer buffer, ref SerializeState state, Temperature value) { buffer.WriteDouble(value.Celsius); } public void Deserialize(ref TReadBuffer buffer, ref DeserializeState state, ref Temperature value) { value = new Temperature(buffer.ReadDouble()); } } ``` On a member, the formatter applies to that member only. The built-in factories can be used this way too: ```csharp [MessagePackObject] public class MyClass { // your own formatter, for this member [Key(0)] [MessagePackFormatter(typeof(ColorFormatter<,>))] public Color Background { get; set; } // this Guid as 16 bytes of binary instead of a string [Key(1)] [MessagePackFormatter(typeof(DotNetOptimizedFormatterFactory))] public Guid Id { get; set; } // this string through the intern pool [Key(2)] [MessagePackFormatter(typeof(StringInterningFormatterFactory))] public string? Category { get; set; } } ``` `ForceSizeFormatterFactory` on an integer member always writes it at its full width, whatever the value. ## Reserved Extension Types MessagePack for C# uses some MessagePack extension type codes. Avoid using the same codes for other purposes. Range | Reserved for --|-- \[-128, -1\] | Reserved by the MessagePack specification for predefined types \[30, 120) | Reserved for this library This leaves the following ranges for your use: - \[0, 30) - \[120, 127] Within the reserved ranges, this library uses these type codes: | Code | Type | Used by | | ---- | ---- | --- | | -1 | `DateTime` | The MessagePack timestamp | | 95 | All | Length-prefixed framing (`WithFraming`) | | 97 | Object references | `AllowCircularReferences` | | 98 | All | `WithLz4BlockArray` | | 99 | All | `WithLz4Block` | | 100 | `object` | Typeless | ## Unity support The minimum Unity version is 2022.3.12f1. There are two installation steps; do both. 1. Install `MessagePack` from NuGet using [NuGetForUnity](https://github.com/GlitchEnzo/NuGetForUnity): open NuGet -> Manage NuGet Packages from the menu bar, search "MessagePack" and press Install. 2. Install the `MessagePack.Unity` package by git URL: open the Package Manager window, press `Add Package from git URL...` and enter ``` https://github.com/Cysharp/MessagePack-CSharp.git?path=src/MessagePack.Unity#v4.0.0 ``` `MessagePack.Unity` adds formatters for `Vector2`, `Vector3`, `Vector4`, `Quaternion`, `Color`, `Color32`, `Bounds`, `Rect`, `Keyframe`, `AnimationCurve`, `Matrix4x4`, `Gradient`, `RectOffset`, `LayerMask`, `Vector2Int`, `Vector3Int`, `RangeInt`, `RectInt` and `BoundsInt`. Enable them with `WithUnity()`: ```csharp using MessagePack; using MessagePack.Unity; static readonly MessagePackSerializerOptions UnityOptions = new MessagePackSerializerOptions(MessagePackFormatterFactory.DefaultAot.WithUnity()); ``` IL2CPP cannot create generic types at run time, so base the options on `DefaultAot` there and read the [Native AOT](#native-aot) section, which applies to IL2CPP as well. In a Mono (JIT) build `MessagePackFormatterFactory.Default.WithUnity()` works too. `WithUnity()` also serves the nullable, array and `List` forms of these types, such as `Vector3?`, `Vector3[]` and `List`, and the `WrapMode` and `GradientMode` enums, so under `DefaultAot` they need no `[MessagePackSerializable]` declaration. ### Share types with .NET To talk to a Unity client from a .NET server, reference the `MessagePack.UnityShims` NuGet package on the server and apply the same options. It contains shims for `Vector3` and the other UnityEngine types, so both sides serialize each other's data. ## v3 compatibility options These options are not recommended in v4, but they remain available. They work through reflection instead of the source generator, so they are not available on Native AOT. ### Without attributes (contractless) To serialize types without annotating them, add `WithContractless` to the options. Types without attributes are then written as maps of member names. This also covers anonymous types. ```csharp public class ContractlessSample { public int MyProperty1 { get; set; } public int MyProperty2 { get; set; } } // Create the options once and keep them in a static field. static readonly MessagePackSerializerOptions ContractlessOptions = new MessagePackSerializerOptions(MessagePackFormatterFactory.Default.WithContractless()); var data = new ContractlessSample { MyProperty1 = 99, MyProperty2 = 9999 }; var bin = MessagePackSerializer.Serialize(data, ContractlessOptions); // {"MyProperty1":99,"MyProperty2":9999} Console.WriteLine(MessagePackSerializer.ConvertToJson(bin)); ``` To include non-public members, use `WithContractless(allowPrivate: true)`. The contractless tier uses reflection, so it is not available on Native AOT. ### DataContract compatibility You can use `[DataContract]` instead of `[MessagePackObject]`. On such a type, `[DataMember]` replaces `[Key]` and `[IgnoreDataMember]` replaces `[IgnoreMember]`: `[DataMember(Order = int)]` behaves like `[Key(int)]`, `[DataMember(Name = string)]` like `[Key(string)]`, and a bare `[DataMember]` uses the member name. This keeps shared classes independent of MessagePack for C#. However, `[DataContract]` types are not source generated: they are served through reflection at run time, so they are not available on Native AOT. We recommend the MessagePack for C# annotations when possible. ### Typeless The typeless mode is similar to `BinaryFormatter`: it embeds the .NET type name in the data, so `object` slots and abstract types round-trip without the caller naming a type. ```csharp static readonly MessagePackSerializerOptions TypelessOptions = new MessagePackSerializerOptions( MessagePackFormatterFactory.Default.WithTypeless(TypelessTypeLoader.AllowedTypes(typeof(MyClass)))); object mc = new MyClass { Age = 10, FirstName = "hoge", LastName = "huga" }; // The data embeds the assembly-qualified type name. var blob = MessagePackSerializer.Serialize(mc, TypelessOptions); // No type has to be specified: the result is a MyClass. var objModel = MessagePackSerializer.Deserialize(blob, TypelessOptions); ``` The type name is written in the MessagePack `ext` format, type code `100`. The format is the same as v3's `MessagePackSerializer.Typeless`, in both directions. Consider it .NET-specific data that other MessagePack implementations cannot readily read. `TypelessTypeLoader` decides which type names in the data are accepted: | Loader | Behaviour | |---|---| | `TypelessTypeLoader.AllowedTypes(params Type[])` | Accepts the listed types only. List every type that can appear in an `object` or abstract slot, including `Guid`, `DateTime`, enums and collection types. | | `TypelessTypeLoader.Create(Func)` | Your own mapping; return `null` to refuse a name. Use this when a type has been renamed. | | `TypelessTypeLoader.LoadAnyType()` | v3's behaviour: resolves any name with `Type.GetType`. For fully trusted data only; it is marked `[Obsolete]` so that using it produces a warning. | ```csharp // a type was moved to another namespace: translate the old name, then look it up in the list of allowed types var allowed = TypelessTypeLoader.AllowedTypes(typeof(AnotherNamespace.MyClass)); var loader = TypelessTypeLoader.Create(typeName => { if (typeName.StartsWith("SomeNamespace")) { typeName = typeName.Replace("SomeNamespace", "AnotherNamespace"); } return allowed.LoadType(typeName); }); ``` The delegate has the last word on a name. One that passes it on to `Type.GetType` accepts any type the data names, which is what `LoadAnyType` does, so keep that for fully trusted data as well. As in v3, the typeless mode serializes a type that has no `[MessagePackObject]` as a map of its members, private fields and properties included. Data that names an allowed type can therefore set members its public API does not expose. To leave private members out, add `WithContractless()` before `WithTypeless(...)`. Typeless is not available on Native AOT. ## For library authors * **Multi-target your library.** A library that declares `[MessagePackObject]` types or formatters and targets only `netstandard2.x` still works in a `net9.0`+ application, but every object graph that contains one of its types takes a slower path (measured at about 5% on serialize and 8% on deserialize). Add a `net9.0` target (`netstandard2.1;net9.0`) to avoid it. An application can detect the situation by subscribing to the `CompatibilityFallback` event of the resolver, or turn it into an error by setting `ThrowOnLegacyFormatter = true` on the resolver. * **C# 9 is required** where the source generator runs. `net48` and `netstandard2.0` projects default to C# 7.3, so set `9.0` or later in a project that declares `[MessagePackObject]` types. ## Use cases ### MagicOnion [MagicOnion](https://github.com/Cysharp/MagicOnion) is a code-first gRPC framework based on grpc-dotnet and MessagePack. gRPC usually communicates with Protocol Buffers using IDL. But MagicOnion uses MessagePack for C# and does not need IDL. When communicating C# to C#, schemaless (or rather C# classes as schema) is better than using IDL. ### MasterMemory [MasterMemory](https://github.com/Cysharp/MasterMemory) is a read-only in-memory document database for .NET. By specializing in read-only data held in memory, it answers queries 1,900 times faster than SQLite, with zero allocation. Choosing MessagePack for C# as its storage format is what lets the data be flexible C# types and the database load fast. ## .NET Foundation This project is supported by the [.NET Foundation](https://dotnetfoundation.org). ## License This library is under MIT License.