.NET Binary Object Serialization without Marking as Serializable

 

Okay, so you got something you need to binary serialize in .NET for whatever reason. Perhaps your saving the state of an object for hydration at a later time (most common), but you find yourself in such a situation where you are unable to mark all of the classes (or classes within properties) as “Serializable”. Perhaps the base object (or the child) is in another library or even a third party component, which basically means you can forget about using the built in BinaryFormatter from .NET. While I understand the purpose of .NET enforcing the use of the Serializable attribute for Binary Serialization (to ensure developers are making conscious decisions as to what should be allowed), at the same time nothing has bothered me more than the ability to not be able to override this and use the BinaryFormatter against an object not marked Serializable.

So I began my search in skewering the web. I needed something that would be simple, lightweight and I could plug in fast.

Protobuf-NET

 I found: http://code.google.com/p/protobuf-net/ which seemed like an obvious choice and is quite popular. But from all the examples I could find it was not the simplest to use from the perspective I wanted – leaving my code class clean without any proprietary attributes on my object. Protobuf also required that if I wanted to dynamically serialize an object that didn’t have attributes for serialization, that I specify each of the objects specifically in question. Okay, what else can I find…

SharpSerializer

Then I came across SharpSerializer: http://www.sharpserializer.com. SharpSerializer is a fantastic simple littler serializer that does exactly what I needed it too. Simply take your object, serialize, no need to specify any attributes or objects. You can programmatically tell it to ignore certain types (in case you don’t need them or there is a redundancy). It allows for size optimization that works well (not super-fast). Check out the tutorial here:

http://www.sharpserializer.com/en/tutorial/index.html#a25

*Note – the only potential flaw is that it does not serialize Fields! You must expose any fields with a Property that you want serialized. This normally isn’t an issue for most object design scenarios.

One Comments

  1. Leonid Ganeline says:

    One more serializer without need of usnig Serializabel attributes is the Slim serializer: https://github.com/leo-gan/GLD.SerializerBenchmark. There is also ProtoBuf for .NET from Mark Gravell.

Leave a Reply