Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

MessagePack-CSharp

> 编程语言
Open source

Extremely Fast MessagePack Serializer for C#(.NET, .NET Core, Unity, Xamarin). / msgpack.org[C#]

6.8K stars0 likes0 views
WebsiteGitHub

About

Extremely Fast MessagePack Serializer for C#(.NET, .NET Core, Unity, Xamarin). / msgpack.org[C#]

MessagePack for C# (.NET Framework, .NET 8, Unity, Xamarin)

The extremely fast MessagePack serializer for C#. It is 10x faster than MsgPack-Cli and outperforms other C# serializers. MessagePack for C# also ships with built-in support for LZ4 compression - an extremely fast compression algorithm. Performance is important, particularly in applications like games, distributed computing, microservices, or data caches.

MessagePack has a compact binary size and a full set of general purpose expressive data types. Please have a look at the comparison with JSON, protobuf, ZeroFormatter section and learn why MessagePack C# is the fastest.

Table of Contents

  • Installation
    • NuGet packages
    • Unity
    • Migration notes from v1.x
  • Quick Start
  • Analyzer
  • Built-in supported types
  • Object Serialization
  • DataContract compatibility
  • Serializing readonly/immutable object members (SerializationConstructor)
  • Serialization Callback
  • Union
  • Dynamic (Untyped) Deserialization
  • Object Type Serialization
  • Typeless
  • Security
  • Performance
    • Deserialization Performance for different options
    • String interning
  • LZ4 Compression
    • Attributions
  • Comparison with protobuf, JSON, ZeroFormatter
  • Hints to achieve maximum performance when using MessagePack for C#
    • Use indexed keys instead of string keys (Contractless)
    • Create own custom composite resolver
    • Use native resolvers
    • Be careful when copying buffers
    • Choosing compression
  • Extensions
  • Experimental Features
  • High-Level API (MessagePackSerializer)
    • Multiple MessagePack structures on a single Stream
  • Low-Level API (IMessagePackFormatter<T>)
  • Primitive API (MessagePackWriter, MessagePackReader)
    • MessagePackReader
    • MessagePackWriter
  • Main Extension Point (IFormatterResolver)
  • MessagePackFormatterAttribute
  • IgnoreFormatter
  • Reserved Extension Types
  • Unity support
  • AOT Code Generation (support for Unity/Xamarin)
  • RPC
    • MagicOnion
    • StreamJsonRpc
  • How to build
  • Author Info
  • Code of Conduct & .NET Foundation notice

Installation

This library is distributed via NuGet. Special Unity support is available, too.

We target .NET Standard 2.0 with special optimizations for .NET 8+ and .NET Framework. The library code is pure C# (with Just-In-Time IL code generation on some platforms or AOT safe source generators).

NuGet packages

To install with NuGet, just install the MessagePack package:

powershell
Install-Package MessagePack

There are also a range of official and third party Extension Packages available (learn more in our extensions section):

powershell
Install-Package MessagePack.ReactiveProperty
Install-Package MessagePack.UnityShims
Install-Package MessagePack.AspNetCoreMvcFormatter

Unity

For Unity projects, please read the Unity Support section to install.

Migration notes from prior versions

Migrating from a prior major version of MessagePack to the latest? Check out these instructions.

Quick Start

Define the struct or class to be serialized and annotate it with a [MessagePackObject] attribute. Annotate members whose values should be serialized (fields as well as properties) with [Key] attributes.

…

Call MessagePackSerializer.Serialize<T>/Deserialize<T> to serialize/deserialize your object instance. You can use the ConvertToJson method to get a human readable representation of any MessagePack binary blob.

…

By default, a MessagePackObject annotation is required. This can be made optional; see the Object Serialization section and the Formatter Resolver section for details.

Analyzer

The MessagePackAnalyzer package(includes in default) aids with:

  1. Produces compiler warnings upon incorrect attribute use, member accessibility, and more.
  2. Automating attributing of your serializable classes and members.
  3. Optionally improving startup time through AOT formatter generation.

The first two of these features is demonstrated below:

Two assembly-level attributes exist to help with mixing in your own custom formatters with the automatically generated ones:

  • MessagePackKnownFormatterAttribute - Identifies classes that implement IMessagePackFormatter<T>. The T type argument will not produce an analyzer warning when T is used elsewhere in a serializable object. When using a source generated resolver, the resolver will refer to this formatter for the appropriate type(s).
  • MessagePackAssumedFormattableAttribute - Identifies types that are assumed to have an IMessagePackFormatter<T> somewhere, and that will be combined within an IFormatterResolver at runtime to ensure the specified type can be serialized. This attribute will suppress the analyzer warning from using that type although the type does not have a [MessagePackObject] attribute on it.

Built-in supported types

These types can serialize by default:

  • Primitives (int, string, etc...), Enums, Nullable<>, Lazy<>
  • TimeSpan, DateTime, DateTimeOffset, DateOnly (.NET 6+), TimeOnly (.NET 6+)
  • Guid, Uri, Version, StringBuilder, decimal, Type
  • BigInteger, Complex, Half (.NET 5+), Rune (.NET 5+), Int128 (.NET 7+), UInt128 (.NET 7+)
  • Memory<byte>, ReadOnlyMemory<byte>, ReadOnlySequence<byte>
  • System.Numerics.Vector2, Vector3, Vector4, Quaternion, Matrix3x2, Matrix4x4
  • Array[], Array[,], Array[,,], Array[,,,], ArraySegment<>, BitArray
  • KeyValuePair<,>, Tuple<,...>, ValueTuple<,...>
  • ArrayList, Hashtable
  • List<>, LinkedList<>, Queue<>, Stack<>, HashSet<>, ReadOnlyCollection<>, SortedList<,>
  • IList<>, ICollection<>, IEnumerable<>, IReadOnlyCollection<>, IReadOnlyList<>
  • Dictionary<,>, IDictionary<,>, SortedDictionary<,>, ILookup<,>, IGrouping<,>, ReadOnlyDictionary<,>, IReadOnlyDictionary<,>
  • ObservableCollection<>, ReadOnlyObservableCollection<>
  • ISet<>,
  • ConcurrentBag<>, ConcurrentQueue<>, ConcurrentStack<>, ConcurrentDictionary<,>
  • Immutable collections (ImmutableList<>, etc)
  • Custom implementations of ICollection<> or IDictionary<,> with a parameterless constructor
  • Custom implementations of IList or IDictionary with a parameterless constructor

You can add support for custom types, and there are some official/third-party extension packages for:

  • ReactiveProperty
  • for Unity (Vector3, Quaternion, etc...)
  • F# (Record, FsList, Discriminated Unions, etc...)

Please see the extensions section.

MessagePack.Nil is the built-in type representing null/void in MessagePack for C#.

Object Serialization

MessagePack for C# can serialize your own public class or struct types. By default, serializable types must be annotated with the [MessagePackObject] attribute and members with the [Key] attribute. Keys can be either indexes (int) or arbitrary strings. If all keys are indexes, arrays are used for serialization, which offers advantages in performance and binary size. Otherwise, MessagePack maps (dictionaries) will be used.

If you use [MessagePackObject(keyAsPropertyName: true)], then members do not require explicit Key attributes, but string keys will be used.

…

All public instance members (fields as well as properties) will be serialized. If you want to ignore certain public members, annotate the member with a [IgnoreMember] attribute.

Please note that any serializable struct or class must have public accessibility; private and internal structs and classes cannot be serialized! The default of requiring MessagePackObject annotations is meant to enforce explicitness and therefore may help write more robust code.

Should you use an indexed (int) key or a string key? We recommend using indexed keys for faster serialization and a more compact binary representation than string keys. However, the additional information in the strings of string keys can be quite useful when debugging.

When classes change or are extended, be careful about versioning. MessagePackSerializer will initialize members to their default value if a key does not exist in the serialized binary blob, meaning members using reference types can be initialized to null. If you use indexed (int) keys, the keys should start at 0 and should be sequential. If a later version stops using certain members, you should keep the obsolete members (C# provides an Obsolete attribute to annotate such members) until all other clients had a chance to update and remove their uses of these members as well. Also, when the values of indexed keys "jump" a lot, leaving gaps in the sequence, it will negatively affect the binary size, as null placeholders will be inserted into the resulting arrays. However, you shouldn't reuse indexes of removed members to avoid compatibility issues between clients or when trying to deserialize legacy blobs.

Example of index gaps and resulting placeholders:

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.SerializeToJson(new IntKeySample()));

If you do not want to explicitly annotate with the MessagePackObject/Key attributes and instead want to use MessagePack for C# more like e.g. Json.NET, you can make use of the contractless resolver.

…

If you want to serialize private members as well, you can use one of the *AllowPrivate resolvers.

csharp
[MessagePackObject]
public class PrivateSample
{
    [Key(0)]
    int x;

    public void SetX(int v)
    {
        x = v;
    }

    public int GetX()
    {
        return x;
    }
}

var data = new PrivateSample();
data.SetX(9999);

// You can choose either StandardResolverAllowPrivate
// or ContractlessStandardResolverAllowPrivate
var bin = MessagePackSerializer.Serialize(
  data,
  MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Options);

If you want to use MessagePack for C# more like a BinaryFormatter with a typeless serialization API, use the typeless resolver and helpers. Please consult the Typeless section.

Resolvers are the way to add specialized support for custom types to MessagePack for C#. Please refer to the Extension point section.

DataContract compat

Issues· 148 open

View all issuesOpen on GitHub
  • #2299

    [GLD Serializer Benchmark] C# MessagePack-CSharp 2.5.302 — spec compliance misses

    Updated Sep 16, 2026
  • #2297

    Add ExcludeFromCodeCoverage attribute to generated code.

    Updated Sep 11, 2026
  • #2184

    No possibility to disable source generation for UnionAttribute

    Updated Sep 11, 2026
  • #2133

    Compile Error CS0426 with Custom Formatter for Generic Type in External Package

    Updated Aug 17, 2026
  • #2292

    Missing `.meta` files cause Unity to reject the MessagePack package

    Updated Aug 15, 2026
  • #2289

    IntelliSense error due to MessagePack source generator

    Updated Aug 5, 2026
  • #1449

    Non-default constructor is used to deserialize without a `[SerializationConstructor]` attribute

    awaiting-approvalUpdated Jul 31, 2026
  • #1918

    Formatter singletons should be accessible via `internal` static readonly fields

    Updated Jul 31, 2026
  • #57

    Support for circular references in object graph

    enhancementawaiting-approvalUpdated Jul 31, 2026
  • #2283

    Generator and analyzer crash with IndexOutOfRangeException on a closed generic struct from a referenced assembly

    Updated Jul 27, 2026

> Tags

C#c-sharplz4messagepackmsgpack

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 23, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言