.Net implementation: binary serialization format used by Google

Protobuf-net is the .net implementation of protocol buffers. Protocol buffers is the the binary serialization format used by Google for data communications. The advantages of using protocol buffer include:

  • small in size – efficient data storage (far smaller than xml)
  • cheap to process – both at the client and server
  • platform independent – portable between different programming architectures
  • extensible – to add new data to old messages

Protobuf-net can serialize the .net objects to their binary streams and deserialize the binary streams to .net objects with efficient compression.

Protobuf-net can be used with your existing project by including its .dll. The package can be downloaded from . Follow the steps below to use it with existing project in Monodevelop.

  1. Create a C# console project.
  2. In the References, click on .Net Assembly and add the protobuf-net.dll.
  3. Now you can use the Protobuf library in your project.
  4. Use Serializer class to serialize and deserialize the data.

Sample code

using System;
using System.IO;
using ProtoBuf;

namespace protobufnet
{
	[ProtoContract]
	public class Person
	{
	    [ProtoMember(1)]
	    public string Name { get; set; }
	    [ProtoMember(2)]
	    public int Age { get; set; }
	    [ProtoMember(3)]
	    public DateTime DateOfBirth { get; set; }        
	    [ProtoMember(4)]        
	    public Address Address { get; set; }
	}
	
	[ProtoContract]
	public class Address
	{
	    [ProtoMember(1)]
	    public string Number { get; set; }
	    [ProtoMember(2)]
	    public string StreetName { get; set; }
	}
	
	class MainClass
	{		
		public void serializeDeserializeData()
		{
			var person = new Person {
		        Name = "Fred",
		        Address = new Address {
		            Number = "Flat 1",
		            StreetName = "The Meadows"
		        }
		    };
		    using (var file = File.Create("person.bin")) {
		        Serializer.Serialize(file, person);
		    }	
			
			Person newPerson;
            using (FileStream file = File.OpenRead("person.bin"))
            {
                newPerson = Serializer.Deserialize<Person>(file);
            }

            Console.WriteLine("expected Name {0}", person.Name);
            Console.WriteLine("actual Name {0}", newPerson.Name);
		}
		
		public static void Main (string[] args)
		{			
			MainClass mainclass = new MainClass();
			mainclass.serializeDeserializeData();
			Console.WriteLine ("Serialization and Deserialization completed!");
		}
	}
}