BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Thanks to a Utility Library by Erik Bergstedt, Protobuf for .NET Just Got Easier

Thanks to a Utility Library by Erik Bergstedt, Protobuf for .NET Just Got Easier

Bookmarks

Protobuf is a wire format created by Google. Formally known as Protocol Buffers, it is a compact binary format that discards readability and extensibility for size and performance. In order to deserialize a Protobuf message, the client and server must agree on the specific fields in the message ahead of time. (Contrast this with XML or JSON, where the client can examine the message structure at runtime.)

In the .NET version of Protobuf, attributes are used to tag properties with “id” numbers. These are, in turn, used to construct the binary arrays that contain the message. Here is an example,

[ProtoContract]
class Address
{
    [ProtoMember(1)]
   
public string Line1 { get; set; }
    [ProtoMember(2)]
    public string Line2 { get; set; }
}

Using Protobuf in C# can be somewhat tedious, as you normally have to manipulate streams. But with Erik Bergstedt’s Protobuffer library, serialization and deserialization has been reduced to simple one-liners.

var serialize = _simpleSerializer.ToByteArray(GetPerson());
Person deserialize = _simpleDeserializer.FromByteArray<Person>(serialize);

You may be wondering why not add these to the Protobuf directly. Erik wites,

Because this library is opinionated, and hides some functionality which can be undesirable in some situations. There is a sacrifice to pay for simplicity.

For example I am opinionated on how to create the streams, and also the support for GZIP is outside the scope of the original protobuf.

We must be careful to differentiate between bloat and features. If my things were part of the original protobuf, I'd argue it would tangent bloat and not feature.

Protobuffer is offered as open source under the MIT License. Protobuf itself is offered by Google for a variety of platforms and programming languages including C++, Java, JavaScript, Python, and Ruby.

Rate this Article

Adoption
Style

BT