3/31/2016 8:33:14 PM

The code below will hopefully provide a simple but complete example of how you can use the Google based protobuf-net Nuget library. This example will also convert the serialized data to a string for easy storage in a database.


Install-Package protobuf-net

//declare object that needs to be serialized
//each property that needs to be serialized must be assigned a unique integer tag
public class MyObject
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }

//create object
var myObject = new MyObject()
	Id = 1,
	FirstName = "John",
	LastName = "Doe"

//serialize and convert to string (can store this string in a database)
var myObjectString = "";
using (var stream = new System.IO.MemoryStream())
	ProtoBuf.Serializer.Serialize<MyObject>(stream, myObject);
	myObjectString = Convert.ToBase64String(stream.ToArray());

//deserialize from string
var myObject2 = new MyObject();
byte[] myObjectBytes = Convert.FromBase64String(myObjectString);
using (var stream = new System.IO.MemoryStream(myObjectBytes))
	myObject2 = ProtoBuf.Serializer.Deserialize<MyObject>(stream);