Quick Intro to Protobuf

Protobuf-net is a .net adaption of Google’s Protocol Buffers and is generally considered to be a really fast serialization/deserialization library.  The target serializable classes are decorated with mainly 3 attributes.

ProtoContract
The target class is decorated with the ProtoContract attributes, indicating that the class can be serialized.

ProtoMember(N)
The ProtoMember attribute indicates the field that will be serialized, while the number N denotes the order in which the property would be serialized. By default, the properties would be serialized in alphabetical order.

ProtoIgnore
As the name suggests, the ProtoIgnore attributes is used to indicate the properties that needs to be ignored while serializing.

Let’s create the example class which we would be serializing.

[ProtoContract]
public class Student
{
  [ProtoMember(1)]
  public string Name { get; set; }
}

In order to serialize the class, you would be using the Static method Serialize.

var stOriginal = new Student() { Name = "jia" };
byte[] array;
           
using (var stream = new System.IO.MemoryStream())
{
   ProtoBuf.Serializer.Serialize(stream, stOriginal);
   array = stream.ToArray();
}

Similarly, the static method Deserialize can be used to deserialize the object back.

Student stDeserialized;
using (var stream = new System.IO.MemoryStream(array))
{
  stDeserialized = ProtoBuf.Serializer.Deserialize(stream);
}

Easy as that !! Happy Coding !!